what does @classmethod do in python code example
Example 1: class methods in python
from datetime import date
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
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