Class and Object Attributes — Python

Class and Object Attributes — Python

What are class and object attributes? What?s the difference? Why?

Image for post

Before getting into comparison and examples of class and object attributes, let?s first define them ?

  • A class attribute is a variable that belongs to a certain class, and not a particular object. Every instance of this class shares the same variable. These attributes are usually defined outside the __init__ constructor.
  • An instance/object attribute is a variable that belongs to one (and only one) object. Every instance of a class points to its own attributes variables. These attributes are defined within the __init__ constructor.

Why Though?

Why would one need to use class attributes and object attributes?

In a parallel world full of only dogs, each dog has a name and an age. The total number of dogs must be up-to-date at all times. All this must be defined in one class! This might look something like this:

class Dog: dogs_count = 0 def __init__(self, name, age): = name self.age = age print(“Welcome to this world {}!”.format( Dog.dogs_count += 1 def __del__(self): print(“Goodbye {} :(“.format( Dog.dogs_count -= 1

In this class, we have one class attribute dogs_count. This variable keeps track of the number of dogs we have in our doggy world. We have two instance attributes, name and age. These variables are unique to each dog (the attributes of every instance have different memory locations). Every time the __init__ function is executed, dogs_count increases. Likewise ? every time a dog dies (unfortunately dogs don?t live forever in this world), calling the __del__ method, dogs_count decreases.

a = Dog(“Max”, 1)print(“Number of dogs: {}”.format(Dog.dogs_count))b = Dog(“Charlie”, 7)del ac = Dog(“Spot”, 4.5)print(“Number of dogs: {}”.format(Dog.dogs_count))del bdel cprint(“Number of dogs: {}”.format(Dog.dogs_count))Output:Welcome to this world Max!Number of dogs: 1Welcome to this world Charlie!Goodbye Max :(Welcome to this world Spot!Number of dogs: 2Goodbye Charlie :(Goodbye Spot :(Number of dogs: 0

Ah ha! We managed to assign variables that are unique to an object while having one shared variable that all objects contain.

Inheritance Of Attributes

Before opening this topic, let?s take a look at the built-in __dict__ attribute.

class Example: classAttr = 0 def __init__(self, instanceAttr): self.instanceAttr = instanceAttra = Example(1)print(a.__dict__)print(Example.__dict__)Output:{‘instanceAttr’: 1}{‘__module__’: ‘__main__’, ‘__doc__’: None, ‘__dict__’: <attribute ‘__dict__’ of ‘Example’ objects>, ‘__init__’: <function Example.__init__ at 0x7f8af2113f28>, ‘classAttr’: 0, ‘__weakref__’: <attribute ‘__weakref__’ of ‘Example’ objects>}

As we can see, both the class and the object have a dictionary with attribute keys and values. The class dictionary stores multiple built-in attributes that an instance does not contain.

b = Example(2)print(b.classAttr)print(Example.classAttr)b.classAttr = 653print(b.classAttr)print(Example.classAttr)Output:006530

WOAH. Bringing back what I wrote earlier, each instance of a class shares the same class attributes. What happened here? We changed the class attribute of a certain instance, but the shared variable didn?t actually change. Taking a look at the dictionaries of these elements will give further insight:

b = Example(2)print(b.__dict__)print(Example.__dict__)b.classAttr = 653print(b.__dict__)print(Example.__dict__)Output:{‘instanceAttr’: 2}’__module__’: ‘__main__’, ‘__doc__’: None, ‘__dict__’: <attribute ‘__dict__’ of ‘Example’ objects>, ‘__init__’: <function Example.__init__ at 0x7f8af2113f28>, ‘classAttr’: 0, ‘__weakref__’: <attribute ‘__weakref__’ of ‘Example’ objects>}{‘instanceAttr’: 2, ‘classAttr’: 653}{‘__module__’: ‘__main__’, ‘__doc__’: None, ‘__dict__’: <attribute ‘__dict__’ of ‘Example’ objects>, ‘__init__’: <function Example.__init__ at 0x7f8af2113f28>, ‘classAttr’: 0, ‘__weakref__’: <attribute ‘__weakref__’ of ‘Example’ objects>}

Looking closely, we notice that classAttr has been added to the dictionary of the object, with its modified value. The class?s dictionary remained the same, which shows that class attributes can behave as instance attributes sometimes.


To sum this up, class and object attributes are extremely useful but can get messy when used together. Class attributes are favorable when each object needs to share one variable, such as a counter. Object attributes have the advantage when each unique object needs its own values, something that makes them different from other objects.


No Responses

Write a response