Object and Class Attributes in Python Object-Oriented Programming

Alexandre Dutertre
5 min readMay 26, 2022

--

Here is the first article about Python! This article will talk about what is needed to know to start OOP (Object-Oriented Programming) in Python.

To do OOP, we need to create a class that is used afterwards to create objects. Classes are data types defined by the user to create a new type of “variable” which will have its own set of variables and functions associated with it.

Attributes are specific features an object will have, it can be a field (variables inside a class), a method (functions inside a class) or a anything else.

To create a class, we just need to use the class header.

class Square:
pass

A perfectly valid class was created here! The object created from the class is called an instance.

What are class attributes and how to create them

Now that we defined what exactly is a class and what is an instance, let’s look at what are class attributes.

Class attributes are attributes created inside a class. Which means they are defined outside the constructor method. They are shared by all instances of the class and can be called by the class or its instances with class.attribute. If the attribute is a variable, we have 3 possible syntaxes that will define the access modifier of the variable:

  • attr_name: public, it is accessible from any part of the program even outside the class;
  • _attr_name: protected, accessible only from within the class and the sub-classes;
  • __attr_name: private, gives a strong suggestion not to touch it from outside the class. Any attempt will give an AttributeError.

Taking a look at the Square class defined above, we can also define attributes and save it in a file named “square.py”.

class Square:
number_of_instances = 0
__size = 5
def area(self):
# return the area of the square

If we have an instance named my_square in “main.py”, we can call my_square.area to get the value 25.

With the way my attributes are created, every instance of the class will have the same area. Let’s see how to resolve that problem.

What are instance attributes and how to create them

As I said above, class attributes are defined outside the constructor. Which means that instance attributes are defined inside it. The constructor is a specific method that will be automatically called when the instance is created, its name is __init__. As the opposite, there is the destructor (__del__) which is called when we delete the instance.

Let’s modify the class:

class Square:
number_of_instances = 0
def __init__(self, size=0):
if not isinstance(size, int):
raise TypeError('size must be an integer')
if size < 0:
raise ValueError('size must be >= 0')
self.__size = size
Square.number_of_instances += 1
def __del__(self):
Square.number_of_instances -= 1
def area(self):
return self.__size ** 2

Now the size is an instance attribute, which means we can have different size for each instance. Something that we could already see in the previous version of the class, is that methods have a parameter named “self”, this parameter refers to the instance and is automatically called when we use a method.

Now, to give a size to my square and print its area, the code in “main.py” will look like that:

#!/usr/bin/python3
Square = __import__('square').Square
my_square1 = Square(5)
my_square2 = Square(2)
print("area of my_square1 = {}".format(my_square1.area()))
print("area of my_square2 = {}".format(my_square2.area()))

Now we have two squares with different sizes! But if we want to print the size or modify it, how can we do it? We use getters and setters.

@property
def size(self):
return self.__size
@size.setter
def size(self, value):
if not isinstance(value, int):
raise TypeError('value must be an integer')
if value < 0:
raise ValueError('value must be >= 0')
self.__size = value

We can see that both methods have the same name but have different utility.

We can also have static methods (method that doesn’t need the class) with “@staticmethod” or class methods (method returning a new instance) with ”@classmethod” and so on.

Differences between the two types

As seen above, there are several differences between class and instance attributes.

Class attributes are common elements between all instances of the class. They are defined at the top of the class and outside methods, below the class header. They can be called by instanceName.attribute or className.attribute.

Instance attributes are defined inside the constructor and are uniques to the instance, other instances can’t access other instances’ attributes. The only way to call instance attributes is with instanceName.attribute.

Pros and cons of each types

Since class attributes are shared between all instances, it’s really easy to follow the value of those attributes. But as all instances have the same value, the thing possible to do with it are quite limited.

For instance attributes, they are automatically deleted when their instance gets deleted as well. Which means that they are no risk of memory leaks. They are easy to get and set and they can be used easily by the methods as seen above in the example of area and size. However, it’s harder to keep track of an instance value as only their instance can access them.

How Python deals with the object and class attributes using __dict__

__dict__ is a method returning a dictionary with all attributes of a class or an instance. Each instance is stored in a dictionary. It is used the following way: class.__dict__ or instance.__dict__

#!/usr/bin/python3
Square = __import__('square').Square
my_square1 = Square(5)
my_square2 = Square(2)
print(my_square1.__dict__)
print(my_square2.__dict__)
print(Square.__dict__)

Conclusion

  • class are created with the class header
  • class attributes are defined outside __init__ and are accessible by all instances
  • instance attribute are defined inside __init__ and are accessible only by the instance.
  • We can print the informations of the class or the instance with __dict__

Sources

https://www.tutorialsteacher.com/articles/class-attributes-vs-instance-attributes-in-python#:~:text=Class%20attributes%20are%20the%20variables,an%20instance%20of%20a%20class.

https://thepythonguru.com/python-object-and-classes/#:~:text=Classes%20commonly%20contains%20data%20field,time%20new%20object%20is%20created.

https://www.tutorialsteacher.com/python/public-private-protected-modifiers

--

--

Alexandre Dutertre

Student of Holberton School in Laval, France (Cohort #17)