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