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这个对象的另外一个类方法。但是使用了不同的传参手段和处理方式。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM