Class and Object Attributes — Python

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

Inheritance Of AttributesBefore 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:006530WOAH.

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.

ConclusionTo 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.

.. More details

Leave a Reply