Python - Class Attributes



Built-In Class Attributes

Every Python class keeps the following built-in attributes and they can be accessed using the dot operator like any other attribute −

  • __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. This attribute is "__main__" in interactive mode.

  • __bases__ − A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.

Access Built-In Class Attributes

For the above class, let us try to access all these attributes −

class Employee:
   def __init__(self, name="Bhavana", age=24):
      self.name = name
      self.age = age
   def displayEmployee(self):
      print ("Name : ", self.name, ", age: ", self.age)

print ("Employee.__doc__:", Employee.__doc__)
print ("Employee.__name__:", Employee.__name__)
print ("Employee.__module__:", Employee.__module__)
print ("Employee.__bases__:", Employee.__bases__)
print ("Employee.__dict__:", Employee.__dict__ )

It will produce the following output

Employee.__doc__: None
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: (<class 'object'>,)
Employee.__dict__: {'__module__': '__main__', '__init__': <function Employee.__init__ at 0x0000022F866B8B80>, 'displayEmployee': <function Employee.displayEmployee at 0x0000022F866B9760>, '__dict__': <attribute '__dict__' of 'Employee' objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>, '__doc__': None}

Class Variables

In the above Employee class example, name and age are instance variables, as their values may be different for each object. A class attribute or variable whose value is shared among all the instances of an in this class. A class attribute represents a common attribute of all objects of a class.

Class attributes are not initialized inside __init__() constructor. They are defined in the class but outside any method. They can be accessed by the name of the class in addition to the object. In other words, a class attribute is available to the class as well as its object.

Example

Let us add a class variable called empCount in Employee class. For each object declared, the __init__() method is automatically called. This method initializes the instance variables as well as increments the empCount by 1.

class Employee:
   empCount = 0
   def __init__(self, name, age):
      self.__name = name
      self.__age = age
      Employee.empCount += 1
      print ("Name: ", self.__name, "Age: ", self.__age)
      print ("Employee Number:", Employee.empCount)

e1 = Employee("Bhavana", 24)
e2 = Employee("Rajesh", 26)
e3 = Employee("John", 27)

Output

We have declared three objects. Every time, the empCount increments by 1.

Name: Bhavana Age: 24
Employee Number: 1
Name: Rajesh Age: 26
Employee Number: 2
Name: John Age: 27
Employee Number: 3
Advertisements