Python Class Methods

Class methods are functions defined in a class that refer to the class as a whole rather than an individual instance of a class.

class MyClass:

    def method(cls):
        return 42

MyClass.method()  # Call the Class Method

A method is made a class method by adding the @classmethod decoration. Class methods take the cls object as the first parameter.

To understand what this means, consider this class that defines a dog. Dogs generally have their own name, but all dogs are, well, 'dogs'. Our dog class will have a name that's individual to each Dog, and an animal type that is shared by all Dogs (returned to us by a static method)

class Dog:

    allDogsAnimalType = 'Dog'      # a class variable, shared by all

    def __init__(self, name):
        self.thisDogsName = name   # an instance variable, specific to each instance of Dog 

    def getName(self):
        return self.thisDogsName
    def getAnimalType(cls):
        return cls.allDogsAnimalType

Then to call the methods:

myDog = Dog("spot")
print(f"Class method: Animal type is {Dog.getAnimalType()}.")
print(f"Instance method: Dog's name is {myDog.getName()}.")


Class method: Animal type is Dog.
Instance method: Dog's name is spot.


A class method is often used in the Factory pattern, which allows you to decide, at run time, which class an object will be.