classmethod with self code example
Example 1: python: @classmethod
class Float:
def __init__(self, amount):
self.amount = amount
def __repr__(self):
return f'<Float {self.amount:.3f}>'
@classmethod
def from_sum(cls, value_1, value_2):
return cls(value_1 + value_2)
class Dollar(Float):
def __init__(self, amount):
super().__init__(amount)
self.symbol = '€'
def __repr__(self):
return f'<Euro {self.symbol}{self.amount:.2f}>'
print(Dollar.from_sum(1.34653, 2.49573))
Example 2: 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())