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.
Python
Copy Code
class MyClass: @classmethod 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)
Python
Copy Code
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 @classmethod def getAnimalType(cls): return cls.allDogsAnimalType
Then to call the methods:
Python
Copy Code
myDog = Dog("spot") print(f"Class method: Animal type is {Dog.getAnimalType()}.") print(f"Instance method: Dog's name is {myDog.getName()}.")
Output
Class method: Animal type is Dog. Instance method: Dog's name is spot.
Notes
A class method is often used in the Factory pattern, which allows you to decide, at run time, which class an object will be.