Python Class Attributes VS Instance Attributes

Maroua alaya
5 min readMay 24, 2021

Hello again, it’s my first time to write about Python programming and specially about Class and instance attributes…I think it was amazing to learn python. Let’s get started…

First, we need to ask some quetions:

Why Python programming is awesome,

What’s a class attribute and what’s an instance attribute,

What are all the ways to create them and what is the Pythonic way of doing it,

What are the differences between class and instance attributes,

How does Python deal with the object and class attributes using the __dict__

In the beginning, I’m going to answer the top questions about Python: So why is Python so popular? Let’s find out below:

Guido van Rossum was creating python in the 1980s, he made sure to design it to be a general-purpose language. One of the main reasons for the popularity of python would be its simplicity in syntax so that it could be easily read and understood even by amateur developers also.

Python is one of the top three most popular programming languages in 2019 and everybody is learning Python either to make their life easier or to expand their job opportunities.

Python is often used in:

Data science and machine learning

Web development

Automation

In fact, if you want to get into data science and machine learning, Python is THE language that you must learn.

Now, we will move to explain Class Attributes VS Instance Attributes but before that, we need to talk about Object Oriented Programming (OOP):

Object-oriented programming, or OOP for short, is a programming language model used for software design. It organizes its design around data or objects, rather than functions and logic. An object, in this model, is a data field that has unique attributes and behavior. It can be a something physical, like a person that’s described by their name and address, or a small computer program like a widget. As an object oriented language, Python provides two scopes for attributes: class attributes and instance attributes.

  • What’s a class attribute

A class attribute is a Python variable that is owned by a class rather than a particular object. It is shared between all the objects of this class and it is defined outside the initializer method of the class.

  • How to create it

Primary, we need to create a class:

A class is a blueprint for the object.

We can think of class of a rectangle which contains all the details about the height, width, area, perimeter etc. Based on these descriptions, we can study about the rectangle. Here, a rectangle is an object.

The example for class of rectangle can be :

""" Module Rectangle"""class Rectangle:   """ a rectangle class that define a rectangle"""   pass

Here, we use the class keyword to define an empty class Rectangle. From class, we construct a class attribute as show the example bellow:

""" Module Rectangle"""class Rectangle:   """ a rectangle class that define a rectangle"""   # A class variable, counting the number of instances   number_of_instances = 1
print("{:d} instances of Rectangle".format(Rectangle.number_of_instances))

Output

1 instances of Rectangle
  • What’s an instance attribute

An instance attribute is a Python variable belonging to only one object. This variable is only accessible in the scope of this object and it is defined inside the init() method also Instance Attributes are unique to each object.

Creating Instance Pythonic and non-Pythonic

A non-Pythonic way would be like this:

""" Module Rectangle"""class Rectangle:   """ a rectangle class that define a rectangle"""def __init__(self,width=0, height=0):
if not (isinstance(width, int) or isinstance(height, int)):
raise TypeError("size must be an integer")

if width < 0 or height < 0:
raise ValueError("size must be >= 0")
self.__width = width
self.__height = height

def area(self):
return (self.__height * self.__width)

The Pythonic way would be like this:

""" Module Rectangle"""class Rectangle:   """ a rectangle class that define a rectangle"""   def __init__(self, width=0, height=0):
self.height = height
self.width = width
@property
def width(self):
""" width function to retrieve the width"""
return self.__width
@width.setter
def width(self, value):
""" width function to set the value to the width
if type(value) is not int:
raise TypeError("value must be an integer")
elif value < 0:
raise ValueError("message value must be >= 0")
else:
self.__width = value
@property
def height(self):
return self.__height
@height.setter
def height(self, value):
if type(value) is not int:
raise TypeError("value must be an integer")
elif value < 0:
raise ValueError("message value must be >= 0")
else:
self.__height = value
def area(self):
return self.__width * self.__height

Differences Between Class and Instance Attributes

The difference is that class attributes is shared by all instances. When you change the value of a class attribute, it will affect all instances that share the same exact value. The attribute of an instance on the other hand is unique to that instance.

The advantages and drawbacks of each of them:

The disadvantage comes when we need to modify the code. The pythonic way of doing it would be to use getter and setter property methods.Unfortunately, it is widespread belief that a proper Python class should encapsulate private attributes .

The advantage of using property allows us to attach code to the self.size attribute and any code assigned the value of size will be called with size in def size.

What does built-in class attribute __dict__ do in Python?

A special attribute of every module is __dict__. This is the dictionary containing the module’s symbol table.

object.__dict__

A dictionary or other mapping object used to store an object’s (writable) attributes.

Example

The following code shows how __dict__ works

class Sequare():
number_of_instances = 0
def __init__(self, size):
self.size = size

sequare_1 = Sequare(2)
sequare_2 = Sequare(3)

print Sequare_1.__dict__
print Sequare_2.__dict__

Outpout

{'size': 2}
{'size': 3}

Conclusion

Python is one of the languages that is witnessing incredible growth and popularity year by year. In 2017, Stackoverflow calculated that python would beat all other programming languages by 2020 as it has become the fastest-growing programming language in the world.

And that’s all, hope you enjoy it! Thanks for reading!!

Maroua Alaya

--

--