Python Attributes

Class and Instance Attributes in Python — Every Coder Must Know the Difference! [+Video Guide]

Today, you are going to learn about the terminology of “attributes” because you need to understand the term and the concepts behind the term to be able to master more advanced stuff.

There are two types of attributes: class attributes and instance attributes.

Class attributes are variables that are defined for the class itself. Instance attributes are variables that are defined for each instance separately. If one instance changes the instance variable, other instance variables are not affected.

Let’s have a look at an example brought up by one of my email subscribers (I have modified it a bit for equality of genders). By the way, sign up for my list to get free Python cheat sheets, code puzzles, Python lessons, and participate in code contests. It’s huge fun — you’ll see! 🤓🐍

class Partner:
    database = []

    def __init__(self, name, age, likes_me):
        self.database.append(self) = name
        self.age = age
        self.likes_me = likes_me

Maria = Partner("Maria", 21, False)
Florian = Partner("Florian", 116, False)
Eve = Partner("Eve", 22, True)
Fiona = Partner("Fiona", 55, True)

for partner in Partner.database:
    if partner.age<25 and partner.likes_me==True:
        print( +"(age " + str(partner.age) + ") likes you!")

Puzzle 1: What is the output of the code snippet?

This example shows both types of attributes: the class attribute “database” and the instance attributes “name”, “age”, and “likes_me”.

The class attribute is defined outside of the constructor __init__(…). You simply create and initialize the variable within the class (e.g. “database = []” in the example). From the outside, we access this variable via the class (e.g. Partner.database) not via the instance (e.g. Maria.database).

However, we actually COULD access the class attribute via each instance like this:

print(Fiona.database == Maria.database)

Puzzle 2: What is the output of the code snippet?

This is different than instance attributes:

print(Fiona.age == Maria.age)

Puzzle 3: What is the output of the code snippet?

The answers to the puzzles are given below at the end of this article.

To sum up, class attributes are shared among all instances of a certain class. Modify a class attribute and all instances will see the change.

Instance attributes are individual to a single instance. Modify an instance attribute and only this instance will have changed data

Here are the responses to the above code puzzles.

## Puzzle 1: Eve(age 22) likes you!
## Puzzle 2: True
## Puzzle 3: False

Leave a Comment

Your email address will not be published. Required fields are marked *