Access Modifiers In Python SANTOSH VERMA
Public Access  All member variables and methods are public by default in Python. So when you want to make your member public, you just do nothing. class Cup: def __init__(self): self.color = None self.content = None def fill(self, beverage): self.content = beverage def empty(self): self.content = None #Driver Code redCup = Cup() redCup.color = "red" redCup.content = "tea" redCup.empty() redCup.fill("coffee")
Protected  Protected member is (in C++ and Java) accessible only from within the class and it’s subclasses. How to accomplish this in Python?  The answer is – by convention. By prefixing the name of your member with a single underscore, class Cup: def __init__(self): self.color = None self._content = None # protected variable def fill(self, beverage): self._content = beverage def empty(self): self._content = None #Driver Code cup = Cup() cup._content = "tea“ print(cup.color, cup._content) Output: None tea
Private  By declaring your data member private you mean, that nobody should be able to access it from outside the class.  Python supports a technique called name mangling. This feature turns every member name prefixed with at least two underscores and suffixed with at most one underscore into. class Peak: def _single_method(self): pass def __double_method(self): # for mangling pass class Pyth(Peak): def __double_method(self): # for mangling pass
Access modifiers in Python

Access modifiers in Python

  • 1.
  • 2.
    Public Access  Allmember variables and methods are public by default in Python. So when you want to make your member public, you just do nothing. class Cup: def __init__(self): self.color = None self.content = None def fill(self, beverage): self.content = beverage def empty(self): self.content = None #Driver Code redCup = Cup() redCup.color = "red" redCup.content = "tea" redCup.empty() redCup.fill("coffee")
  • 3.
    Protected  Protected memberis (in C++ and Java) accessible only from within the class and it’s subclasses. How to accomplish this in Python?  The answer is – by convention. By prefixing the name of your member with a single underscore, class Cup: def __init__(self): self.color = None self._content = None # protected variable def fill(self, beverage): self._content = beverage def empty(self): self._content = None #Driver Code cup = Cup() cup._content = "tea“ print(cup.color, cup._content) Output: None tea
  • 4.
    Private  By declaringyour data member private you mean, that nobody should be able to access it from outside the class.  Python supports a technique called name mangling. This feature turns every member name prefixed with at least two underscores and suffixed with at most one underscore into. class Peak: def _single_method(self): pass def __double_method(self): # for mangling pass class Pyth(Peak): def __double_method(self): # for mangling pass