Class Method (@classmethod)

say it: “KLAS METH-ud” /ˈklæs ˈmɛθəd/

A method that belongs to the class, often another way to create objects.

What does @classmethod do?

A class method belongs to the class rather than one object. It's most often used as another way to create objects, like building one from a line of text.

class Customer:
    def __init__(self, name, email):
        self.name, self.email = name, email

    @classmethod
    def from_csv(cls, line):
        name, email = line.split(",")
        return cls(name, email)

ana = Customer.from_csv("Ana,ana@example.com")

Level: Freelancer · More Python terms at this level

Updated