How do object and class attributes work in Python ?
Thato Khosa
Aspiring Full Stack Developer .NET, React, SQL | Committed to Innovation and Growth
Classes and objects are the main aspects of object oriented programming (OOP) and they are very useful in OOP languages such as Python, which is an interpreted general-purpose programming language that was created in 1991 by Guido Van Rossum.
Classes are data type that can be defined by users and which can create objects while objects are instances of class, that is to say a kind of “copy” of a class with particular values. For example, “hello” is a str object, so an instance of the classe str.
What’s a class attribute and how to create it ?
In Python, class attributes are attributes that are shared by all the instances of this class and that can be called by the class or by ist instances. They are owned by the class and defined outside the __init__ method (which is the constructor function). More precisely, class attributes (like attributes in general) refer to the fields and the methods of this class. Fields are variables that belong to an object or a class while methods are functions that belong to a class. To create a class attribute, you can do it this way (We usualy declare it at the top, just below the class header):
class Example
string = "This is a class attribute"
example_1 = Example()
print(example_1.string)
Output:
This is a class attribute:
We can see that?example_1?is an instance of the class?Example?and?string?is a class attribute.
If you update a class attribute by doing, for example:
Example.string = "This is an updated class attribute"
All the instances of the class Examplewill be updated:
example_1.strin
Output:
'This is an updated class attribute'
What’s an instance attribute and how to create it ?
Contrary to class attributes, instance attributes are specific attributes to each instance and they are not shared between them. They are usually defined in the __init__ method (that is often the first method that an user defines when he creates a class), wich is called directly after the creation of a new instance :
class Square
string = "This class defines a square"
def __init__(self, size, color):
self.size = size
self.color = color
A = Square(5, "Blue")
print(A.size)
print(A.color)
Output:
5
Blue:
Here, we still have the class attribute?string?but we have also the __init__ method that defines two instance attributes called?size?and?color(self refers to the current instance).
More:
An instance attribute can be private (starting with “__”). In this case, it can’t be accessed or updated outside the class:
>>> class Square
... def __init__(self, size):
... self.__size = size
...
>>> A = Square(5)
>>> A.size
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Square' object has no attribute 'size'
>>> A.__size
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Square' object has no attribute '__size':
What are the differences between class and instance attributes ?
As shown previously, there are several differences between class attributes and instance attributes.
Firstly, class attributes are defined in the class and outside methods (usually at the top of the class, below the class header) while instance attributes are defined inside the constructor (__init__ method). Moreover, class attributes are accessible to all instances of this class wherehas instance ones are accessible only to one instance. And another is that we can access a class attribute via the class name or an instance when you can access an instance attribute via the instance to which this attribute belongs (if the attribute is private, you can’t access it outside the class).
So we’ve seen the differences of class and instace attributes, now let’s see the advantages and drawbacks of each of them.
What are the advantages and drawbacks of class and instance attributes ?
Class attributes:
They are the same between instances, so they can be used for example as counter if we want to count how many instances have been created or deleted.
Instance attributes:
They allow users to not have memory leaks because they are deleted when an instance is deleted and they are easy to get and set (you can see?getters and setters). Moreover, instance attributes can be used by methods (for example, if you want to compute the area of a square of size?sizewith a method called?area?, you will take as argument the instance attribute?size?).
Class attributes:
All the instances of a class will have the same value so you can only do the same thing with all the instances.
Instance attributes:
They can’t be accessed by other instances so you can’t keep a track of an instance value.
How does Python deal with the object and class attributes using the?__dict__??
To finish, if you want to check all class attributes, instance attributes and values, you can use the __dict__ method, that displays a dictionary containing all of these informations as shown below:
>>> class Square
... string = "I'm a square !"
... def __init__(self, size, color):
... self.size = size
... self.color = color
...
>>> A = Square(5, "Blue")
>>> A.__dict__
{'size': 5, 'color': 'Blue'}
>>> Square.__dict__mappingproxy({'__module__': '__main__', 'string': "I'm a square !", '__init__': <function Square.__init__ at 0x7f56497df670>, '__dict__': <attribute '__dict__' of 'Square' objects>, '__weakref__': <attribute '__weakref__' of 'Square' objects>, '__doc__': None})
You’ve reached the end of this post, I hope you enjoyed it ! Thanks for reading and enjoy coding !