class method cls python code example
Example 1: python classmethod
class point:
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def zero(cls):
return cls(0, 0)
def print(self):
print(f"x: {self.x}, y: {self.y}")
p1 = point(1, 2)
p2 = point().zero()
print(p1.print())
print(p2.print())
Example 2: python classmethod
In [20]: class MyClass:
...: @classmethod
...: def set_att(cls, value):
...: cls.att = value
...:
In [21]: MyClass.set_att(1)
In [22]: MyClass.att
Out[22]: 1
In [23]: obj = MyClass()
In [24]: obj.att
Out[24]: 1
In [25]: obj.set_att(3)
In [26]: obj.att
Out[26]: 3
In [27]: MyClass.att
Out[27]: 3