Class and instance attributes

Brayan Florez
2 min readJan 15, 2020

In order to start we need to understand what is an attribute, as in real life I can say that in Python an attribute is basically a characteristic which something or someone has, such as eyes color, hair and so on.

By saying that now we’re gonna check some concepts

Class attributes

In summary, a class attribute is a variable that is always defined inside the class belonging to it. We have to know also that a class attribute goes outside the constructor method __init__(self, …)

Instance attributes

An instance attribute is a variable that belongs only to one object in the class. This variable is defined inside the constructor method __init__(self, …)

The following is an example in which we can see how to create both of them

class Example:
class_attribute = 'something'
def __init__(self, instance_attribute):
self.instance_attribute = instance_attribute

Differences

We have already said some differences but to make it clear let’s make a comparative chart

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

The attributes of objects are stored in a dictionary so each instance is stored in a dictionary

Pythonic way of creating class and instance attributes

The “Pythonic” way of creating these attributes must be using the decorators setter and getter. Since it gets easier to modify the code.

class Square:
def __init__(self, size=0):
self.__size = size
@property
def size(self):
return(self.__size)
@size.setter
def size(self, value):
if not isinstance(value, int):
raise TypeError('size must be an integer')
elif value < 0:
raise ValueError('size must be >= 0')
else:
self.__size = value
def area(self):
return(self.size**2)

Advantages and disadvantages

Advantages of class attributes:

  • They store data that is relevant to all instances

Disadvantages of class attributes:

  • You are not be able to use them to do different things on different objects since it’s not possible to have two instances with different values

Advantages of instance attributes:

  • They are threw away once the instance is deleted

Disadvantages of instance attributes:

  • You can’t keep track of values between instances

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response