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這個對象的另外一個類方法。但是使用了不同的傳參手段和處理方式。
標簽:name,如何,Python,age,classmethod,year,def,cls
總結
以上是生活随笔為你收集整理的python中classmethod的用法_Python中的@classmethod是如何使用的?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中用来回溯异常的模块_pyt
- 下一篇: 判断数组中某个元素除自身外是否和其他数据