from datetime import date # random Person class Person: def __init__(self, name, age): self.name = name self.age = age @classmethod def from_birth_year(cls, name, birth_year): # Since `cls` refers to the class itself (`Person`), calling this # `classmethod` creates an instance of `Person`. return cls(name, date.today().year - birth_year) def display(self): print(f"{self.name}'s age is: {self.age}") bob = Person("Bob", 25) bob.display() # Bob's age is: 25 alice = Person.from_birth_year("Alice", 1985) alice.display() # Alice's age is: 39
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter