Learn Python Programming

Python – Attributes


Classes are nothing but blueprints of real world objects. Now when comes to the real world objects, it has some certain properties.

For example: If we see an employee having property of name, employee ID, employee’s progress percentage in a certain project etc. And that is what really defines the blueprint. When you model the object from the real world into the programming world, you would be defining its attributes or its property because that is how you represent it.

Class attributes are the attributes which are owned by the class itself. They will be shared by all the instances of the class.

There are two types of attributes:

  • Built-in Attributes
  • User Defined Attributes

Built-in Attributes

Built-in attributes are made available on a python class object by python itself. There are some certain properties which you need to think.

Built-in attributes usually contains meta information about the class or that object.

  • __dict__ : Dictionary containing the class’s namespace
  • __doc__ : Class documentation string or None if undefined
  • __name__ : Class name
  • __module__ : Module name in which the class is defined
  • __bases__ : A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list

Don’t be confused with the underscore underscore in built-in attributes. It doesn’t mean anything special. It is just a way to write python special attributes. It’s just a visual recognition that it is not your usual attribute, but it is either a built-in or it is something else.

class Myclass():

    '''
        Explaining the Built in Attributes
    '''
    empcount=0
    
print("Myclass.__dict__ : ", Myclass.__dict__)
print("Myclass.__doc__ : ", Myclass.__doc__)
print("Myclass.__name__ : ", Myclass.__name__)
print("Myclass.__module__ : ", Myclass.__module__)
print("Myclass.__bases__ : ", Myclass.__bases__)

#OUTPUT
Myclass.__dict__ :  {'__module__': '__main__', '__doc__': '\n        Explaining the Built in Attributes\n    ', 'empcount': 0, '__dict__': <attribute '__dict__' of 'Myclass' objects>, '__weakref__': <attribute '__weakref__' of 'Myclass' objects>}
Myclass.__doc__ :
        Explaining the Built in Attributes

Myclass.__name__ :  Myclass
Myclass.__module__ :  __main__
Myclass.__bases__ :  (<class 'object'>,)

User Defined Attributes

Attributes are created inside the class definition. You can dynamically create new attributes for existing instances of a class. There is no restrictions on that.

There are three kind of attributes:

  • Public – Public attributes can and should be freely used.
  • Private – Private attributes can only be accessed inside of the class definition.
  • Protected – Protected attributes are only accessible from within the class and it’s subclasses.

Let us understand with the below example.

class Sharequery():
    def __init__(self):
        self.__pri = ("I am Private")
        self._pro = ("I am Protected")
        self.pub = ("I am Public")


obj = Sharequery()

#accessing public attribute
print(obj.pub)

#accessing protected attribute
print(obj._pro)

#accessing private attribute, this will throw error.
print(obj._pri)

#OUTPUT
I am Public
I am Protected
Traceback (most recent call last):
  File "public_private_protected.py", line 11, in <module>
    print(obj._pri)
AttributeError: 'Sharequery' object has no attribute '_pri'

Private Methods

When the attributes of an object can only be accessed inside the Class, it is called Private. Python uses two underscores to hide a method. Two underscores can also be used to hide a variable.

You can not access private method directly outside the class. If used it will show error.

class Myclass:
    def myPublicMethod(self):
        print('Public Method!')
    def __myPrivateMethod(self):
        print('Private Method!')


obj = Myclass()
obj.myPublicMethod()

obj.__myPrivateMethod()

#OUTPUT
Public Method!
Traceback (most recent call last):
  File "priavte_method.py", line 11, in <module>
    obj.__myPrivateMethod()
AttributeError: 'Myclass' object has no attribute '__myPrivateMethod'

But you can access Private methods using one underscore (‘_’) with the class name. Please have a look on the below example.

class Myclass:
    def myPublicMethod(self):
        print('Public Method!')
    def __myPrivateMethod(self):
        print('Private Method!')


obj = Myclass()
obj.myPublicMethod()

obj._Myclass__myPrivateMethod()

#OUTPUT
Public Method!
Private Method!