Class And Instance Attributes

Mouadh Amemri
3 min readOct 5, 2021

--

What is Object Oriented Programming (OOP):

Object Oriented Programming is not a programming language, but rather a model in which programs are organized around data or objects. OOP uses the concept of objects and classes.

For instance, an object could represent a person with properties like a name, age, and address and behaviors such as walking, talking, breathing, and running. Or it could represent an email with properties like a recipient list, subject, and body and behaviors like adding attachments and sending

OOP

Instance Attribute:

are attributes or properties attached to an instance of a class. Instance attributes are defined in the constructor.

Instance attribute

For example:

foo = MyClass(2)
foo.class_var
## 1
foo.class_var = 2
foo.class_var
## 2
MyClass.class_var
## 1

Class Attribute:

are the variables defined directly in the class that are shared by all objects of the class.

Class attribute

For example:

foo = MyClass(2)
foo.class_var
## 1
MyClass.class_var = 2
foo.class_var
## 2

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.

# #

What are the advantages and drawbacks of each of them:

+ And -

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

A __dict__ is a dictionary or maping objet used to store an object’s attributes. How does Python deal with the object and class attributes using the __dict__ ? Well, each instance is stored in a dictonary.

In conclusion:

Class attributes seem to be underused in Python; a lot of programmers have different impressions of how they work and why they might be helpful.

My take: Python class variables have their place within the school of good code. When used with care, they can simplify things and improve readability. But when carelessly thrown into a given class, they’re sure to trip you up.

--

--