Link Search Menu Expand Document

Create your attributes

Every class defines attributes. In object-oriented programming and Python, there are two types of attributes:

  • 🌐 Class Attributes: These are attributes common to all objects of the class. All objects see the same value.
  • πŸ“ Instance Attributes: These are specific attributes of each object. Each object has a different value.

🌐 The counter attribute is a class attribute. All objects of class Person will have the same value.

πŸ“ The attributes first_name, last_name, and age are instance attributes. Each object of class Person will have a different value.

class Person:
    # Class attribute
    counter = 0

    # Instance attributes
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
        
        Person.counter += 1

If we create two different people:

p1 = Person("Juan", "Prieto", 23)
p2 = Person("Ana", "Fuentes", 25)

Both share the value of counter, a class attribute 🌐.

print(p1.counter) # 2
print(p2.counter) # 2

But each one has its own first_name value, an instance attribute πŸ“.

print(p1.first_name) # Juan
print(p2.first_name) # Ana

Another difference is that since counter is a class attribute, you can access it from the class.

print(Person.counter) # 2

As a final note and to be strictly correct, in this example, we should also decrease the counter if the object is destroyed.

class Person:
    counter = 0

    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

        Person.counter += 1

    def __del__(self):
        Person.counter -= 1

If someone now destroys an object with del, the counter will be updated accordingly.

p1 = Person("Ana", "Ruiz", 0)
print(Person.counter) # 1
del p1
print(Person.counter) # 0