what is a classmethod in python code example
Example 1: class methods in python
from datetime import date
# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)
def display(self):
print(self.name + "'s age is: " + str(self.age))
person = Person('Adam', 19)
person.display()
person1 = Person.fromBirthYear('John', 1985)
person1.display()
Example 2: 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 3: how to use class's in python
class person:
name = "jake"
age = 13
x = vars(person)
print(x)