Python中的@classmethod是如何使用的?

时间:2019-10-22
本文章向大家介绍Python中的@classmethod是如何使用的?,主要包括Python中的@classmethod是如何使用的?使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在写Python程序的时候,特别是实现类方法的时候,通常会用到@staticmethod和@classmethod两种装饰器(function decorator),那这两个装饰器有什么作用呢?在这篇博文中将主要看看@classmethod是如何工作的。

@classmethod是Python内置(built-in)的函数装饰器,其主要作用将类方法中的函数方法(实例方法)转换为类方法。

具体的一个使用方式如下所示:

1 class A():
2     @classmethod
3     def B(cls, arg1, arg2):
4         return cls(arg1, arg2)

看上面代码有点抽象,不明白这么做的意义和作用是啥。没事,通过例子来看看就明白@classmethod是如何工作的。

from datetime import date
class Student(object):

    def __init__(self, name, age):
        self.name = name
        self.age= age
    
    @classmethod
    def from_year(cls, name, birth_year):
        return cls(name, date.today().year - birth_year)


student1 = Student("小王", 15)
student2 = Studeng("小李", 2006)

print(student1.age)
print(student2.age)

从上面可以看出,from_year这个函数是构造student这个对象的另外一个类方法。但是使用了不同的传参手段和处理方式。

原文地址:https://www.cnblogs.com/jielongAI/p/11718535.html