@classmethod

PHOTO EMBED

Thu Feb 22 2024 15:34:38 GMT+0000 (Coordinated Universal Time)

Saved by @aguest #python #classes

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
content_copyCOPY

The `classmethod()` method returns a class method for a given function. A `classmethod` is a method that is bound to a CLASS rather than to an instance of that class. A `classmethod` doesn't require an instance of a class to be created before it can be called. By convention, a `classmethod` takes a first parameter of `cls` representing the class itself and NOT `self` which represents an instance of the class.
https://www.programiz.com/python-programming/methods/built-in/classmethod