Python 3D Academyবাংলা

@classmethod: asking the class itself

🌍 In real life. At a bakery you can order a cake by listing every detail (flavour, size, icing), or just say "one birthday special, please". The bakery itself knows how to make the special. You ask the bakery, not one particular cake.

A class method is a method you call on the class, like Cake.birthday_special(). Instead of self (one object), it gets cls: the class itself. Two jobs it's perfect for:

  • another way to make an object ("from a string", "the default one")
  • facts about the whole class, like how many objects were made

The idea in one sentence: a method marked @classmethod is called on the class and gets the class itself as cls, which makes it perfect for alternative ways to build objects.

Its words:

  • @classmethod: marks a method that works on the class
  • cls: the class itself, so cls(...) makes a new object
  • factory method: a class method that builds an object another way, like Date.from_text("25-12-2024")
class Cake:
    def __init__(self, flavour, layers):
        self.flavour = flavour
        self.layers = layers

    @classmethod
    def birthday_special(cls):
        return cls("chocolate", 3)    # cls is Cake here

c = Cake.birthday_special()
print(c.flavour, c.layers)
cls(...) works just like Cake(...): it makes a new object and runs __init__.

Making an object from text. Dates often arrive as text, like "25-12-2024" from a form. A class method can split the text, turn the pieces into numbers, and hand them to cls(...):

  1. text.split("-") gives ["25", "12", "2024"]
  2. int(...) turns each piece into a number
  3. cls(day, month, year) makes the Date
class Date:
    def __init__(self, day, month, year):
        self.day = day
        self.month = month
        self.year = year

    @classmethod
    def from_string(cls, text):
        day, month, year = text.split("-")
        return cls(int(day), int(month), int(year))

d = Date.from_string("25-12-2024")
print(d.day, d.month, d.year)
print(d.year + 1)

Counting every object. A factory keeps one counter on the wall for the whole factory, not one per robot. A class attribute is that counter, and a class method can report it:

class Robot:
    count = 0                 # one counter, shared by the class

    def __init__(self, name):
        self.name = name
        Robot.count += 1

    @classmethod
    def how_many(cls):
        return cls.count

Robot("R2")
Robot("C3")
print(Robot.how_many())

Why cls instead of the class name? Writing cls(...) instead of Date(...) means a child class that inherits the method makes objects of its own class, not the parent's.

Mistakes and edge cases.

  • Forgetting the decorator. Without @classmethod, Date.from_text("...") passes the text in as cls, and things go wrong.
  • Using self in a class method. There is no object yet; use cls.
  • Changing a counter through self. self.made += 1 makes a new attribute on one object; a class method changes cls.made, the shared one.

Quiz

  1. What does this print?

    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        @classmethod
        def origin(cls):
            return cls(0, 0)
    
    p = Point.origin()
    print(p.x + p.y)
  2. What is cls inside a class method?

    • The class itself
    • The newest object
    • A list of all the objects
  3. What does this print?

    class Ticket:
        sold = 0
    
        def __init__(self):
            Ticket.sold += 1
    
        @classmethod
        def total(cls):
            return cls.sold
    
    Ticket()
    Ticket()
    Ticket()
    print(Ticket.total())
  4. What does this print?

    class Time:
        def __init__(self, hours, minutes):
            self.hours = hours
            self.minutes = minutes
    
        @classmethod
        def from_text(cls, text):
            h, m = text.split(":")
            return cls(int(h), int(m))
    
    t = Time.from_text("09:30")
    print(t.hours * 60 + t.minutes)
  5. Which line has a mistake?

    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        @classmethod
        def origin():
            return cls(0, 0)
    
    print(Point.origin().x)

Coding tasks

  1. Give Point a class method origin() that returns a new Point at (0, 0).

  2. Give Date a class method from_string(text) that turns text like "25-12-2024" into a Date whose day, month and year are numbers.

  3. Write a class Robot with a class attribute count starting at 0. Each new Robot adds 1 to it, and a class method how_many() returns it.