python tutorial - Private Attributes And Methods - learn python - python programming




Private

In the context of class, private means the attributes are only available for the members of the class not for the outside of the class.

  • Suppose we have the following class which has private attributes (__alias):
# p.py
class P:
   def __init__(self, name, alias):
      self.name = name       # public
      self.__alias = alias   # private

   def who(self):
      print('name  : ', self.name)
      print('alias : ', self.__alias)
click below button to copy the code. By Python tutorial team

We create an instance of class P, then trying to access its attributes whether it's public or private:

>>> from p import P
>>> x = P(name='Alex', alias='amen')
>>> x.name
'Alex'
>>> x.alias
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: P instance has no attribute 'alias'
click below button to copy the code. By Python tutorial team
  • For public attribute name, we can access through an instance variable, but not for the private attribute alias. Even we try this:
>>> x.__alias
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: P instance has no attribute '__alias'
click below button to copy the code. By Python tutorial team

still we're not allowed to access it.

  • But here is a magic want. One underscore('_') with the class name will do magic:
>>> x._P__alias
'amen'
click below button to copy the code. By Python tutorial team

The the following call also works as expected:

>>> x.who()
('name  : ', 'Alex')
('alias : ', 'amen')
click below button to copy the code. By Python tutorial team

Private Methods

  • We're going to use the same code as in the previous section but we'll add two methods: foo() and __foo() methods:
# p2.py
class P:
   def __init__(self, name, alias):
      self.name = name       # public
      self.__alias = alias   # private

   def who(self):
      print('name  : ', self.name)
      print('alias : ', self.__alias)

   def __foo(self):          # private method
      print('This is private method')

   def foo(self):            # public method
      print('This is public method')
      self.__foo()
click below button to copy the code. By Python tutorial team

How can we use the private method. If we try:

>>> from p2 import P
>>> x = P('Alex', 'amem')
>>> x.__foo()
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: P instance has no attribute '__foo'
click below button to copy the code. By Python tutorial team

The right way of accessing private method is this:

>>> x._P__foo()
This is private method
click below button to copy the code. By Python tutorial team
  • Of course, calling private method via public will work as expected:
>>> x.foo()
This is public emthod
This is private method
click below button to copy the code. By Python tutorial team

Related Searches to Private Attributes And Methods