📜  Python classmethod()(1)

📅  最后修改于: 2023-12-03 15:18:54.327000             🧑  作者: Mango

Introduction to Python's classmethod()

Python's classmethod() is a built-in method that is used to create a class method from a regular method. A class method is a method that is bound to the class and not the instance of the class.

Syntax

The syntax for classmethod() is as follows:

class MyClass:
    @classmethod
    def my_class_method(cls, arg1, arg2, ...):
        # code
Parameters

classmethod() takes a single argument:

  • method: The method that needs to be converted to a class method.
Example

Here's an example of how to use classmethod():

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_birth_year(cls, name, birth_year):
        age = datetime.date.today().year - birth_year
        return cls(name, age)

person = Person.from_birth_year('John', 1985)
print(person.age)

Output:

36

In the above example, we created a Person class and defined an instance method __init__() to initialize the name and age of a person. We also created a class method from_birth_year() that takes in the name and birth year of a person and returns a new Person object.

Notice the @classmethod decorator before the from_birth_year() method. This decorator is what allows the method to be called on the class instead of an instance of the class.

Conclusion

classmethod() is a powerful tool in Python that allows you to create class methods that are bound to the class and not the instance of the class. This can be helpful in situations where you need to create objects from a method that doesn't have access to the instance variables.