Object-oriented programming · 10 / 26 Theory

Class attributes, class methods and static methods

So far everything your objects store belongs to each object. But sometimes there is data or functions that belong to the class as a whole.

Class and instance attributes

An attribute defined inside the class, outside the methods, is a class attribute: there is a single shared copy. An attribute assigned to self is an instance attribute: each object has its own. If you assign to an object an attribute with the same name as a class one, you create an instance attribute that hides it only for that object.

class Counter:
    total = 0                        # atributo de CLASS: one for all

    def __init__(self, name):
        self.name = name         # atributo de INSTANCE: one per object
        Counter.total += 1

a = Counter("a")
b = Counter("b")
print(Counter.total, a.total, b.total)    # 2 2 2

a.total = 99                       # creates an instance attribute that HIDES the class one
print(a.total, b.total, Counter.total)    # 99 2 2

They are usually used for constants (VAT = 21), counters or common configuration. Beware of class attributes that are lists or dictionaries: they are shared among all the objects. You practice it in Instance counter.

Class methods and static methods

A class method (@classmethod) receives the class as its first argument (cls) instead of the object. It is the way to create alternative constructors. A static method (@staticmethod) receives nothing special: it is an ordinary function stored inside the class because it is related to it.

class Date:
    def __init__(self, day, month, year):
        self.day, self.month, self.year = day, month, year

    @classmethod
    def from_text(cls, text):         # alternative constructor
        day, month, year = (int(x) for x in text.split("/"))
        return cls(day, month, year)

    @staticmethod
    def is_leap(year):               # uses neither the class nor the object
        return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

    def __str__(self):
        return f"{self.day:02d}/{self.month:02d}/{self.year}"

f = Date.from_text("7/11/2026")
print(f)                                  # 07/11/2026
print(Date.is_leap(2028), f.is_leap(2026))   # True False
TypeDeclaredReceivesUsed for
Instance methoddef f(self)The object (self)Working with the data of an object
Class method@classmethodThe class (cls)Alternative constructors, shared data
Static method@staticmethodNothing specialHelper functions related to the class

Using cls(...) instead of the class name makes the alternative constructor work in subclasses too.

Properties: computed attributes

@property turns a method into something read like an attribute, so the value is computed every time and cannot become stale.

class Circle:
    def __init__(self, radius):
        self.radius = radius

    @property
    def area(self):                  # used like an attribute: c.area
        return 3.14159 * self.radius ** 2

c = Circle(2)
print(round(c.area, 2))              # 12.57
c.radius = 3                          # the area is recomputed by itself
print(round(c.area, 2))              # 28.27

Special methods so your objects behave like Python ones

By implementing __add__, __eq__, __lt__, __len__, __iter__, __contains__, __str__… your classes support +, ==, <, len(), for, in and print(). You practice it in Vectors with operators and in Iterable playlist. And how to protect the state with exceptions, in Bank account with exceptions.