@staticmethod and @classmethod
@staticmethod defines a method with no access to the instance or class. @classmethod receives the class as its first argument and is used for alternative constructors.
@staticmethod defines a method with no access to the instance or class. @classmethod receives the class as its first argument and is used for alternative constructors.
class Circle:
PI = 3.14159
def __init__(self, radius):
self.radius = radius
@staticmethod
def validate(r):
return r > 0
@classmethod
def unit(cls):
return cls(1)
c = Circle.unit()
print(c.radius) # 1
Use @classmethod for factory methods that create instances.