在 Python 中,@classmethod
裝飾器用於將類中的一個方法聲明為可以使用ClassName.MethodName()
調用的類方法。 類方法也可以使用類的對象來調用。
@classmethod
是 classmethod() 函數的替代函數。建議使用@classmethod
修飾器代替函數,因為它只是一個語法糖。
- 聲明一個類方法。
- 第一個參數必須是
cls
,可以用來訪問類屬性。 - 類方法只能訪問類屬性,而不能訪問實例屬性。
- 可以使用
ClassName.MethodName()
和對象調用類方法。 - 它可以返回類的對象。
下面的示例聲明了一個類方法。
Example: @classmethod
class Student:
name = 'unknown' # class attribute
def __init__(self):
self.age = 20 # instance attribute
@classmethod
def tostring(cls):
print('Student Class Attributes: name=',cls.name)
上圖中,Student
類包含一個類屬性name
和一個實例屬性age
。 tostring()
方法用@classmethod
裝飾器裝飾,使其成為類方法,可以使用Student.tostring()
調用。 注意,任何類方法的第一個參數必須是cls
,可以用來訪問類的屬性。您可以給第一個參數起任何名字,而不是cls
。
現在,您可以使用類方法,如下所示。
Example: Access Class Method
>>> Student.tostring()
Student Class Attributes: name=unknown
但是,也可以使用對象調用相同的方法。
Example: Calling Class Method using Object
>>> std = Student()
>>> std.tostring()
Student Class Attributes: name=unknown
>>> Student().tostring()
Student Class Attributes: name=unknown
類方法只能訪問類屬性,而不能訪問實例屬性。如果試圖訪問類方法中的實例屬性,將會引發錯誤。
Example: @classmethod
class Student:
name = 'unknown' # class attribute
def __init__(self):
self.age = 20 # instance attribute
@classmethod
def tostring(cls):
print('Student Class Attributes: name=',cls.name,', age=', cls.age)
Example: Access Class Method
>>> Student.tostring()
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
Student.tostring()
File "<pyshell#21>", line 7, in display
print('Student Class Attributes: name=',cls.name,', age=', cls.age)
AttributeError: type object 'Student' has no attribute 'age'
類方法也可以用作工廠方法來獲取類的對象,如下所示。
Example: @classmethod
class Student:
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age # instance attribute
@classmethod
def getobject(cls):
return cls('Steve', 25)
下面調用類方法來獲取對象。
Example: Class Method as Factory Method
>>> std = Student.getobject()
>>> std.name
'Steve'
>>> std.age
25
下表列出了類方法和靜態方法的區別:
@classmethod | @staticmethod |
---|---|
聲明一個類方法。 | 聲明一個靜態方法。 |
它可以訪問類屬性,但不能訪問實例屬性。 | 它不能訪問類屬性或實例屬性。 |
可以使用ClassName.MethodName() 或object.MethodName() 來調用。 | 可以使用ClassName.MethodName() 或object.MethodName() 來調用。 |
它可以用來聲明返回類對象的工廠方法。 | 它不能返回類的對象。 |
原創文章,作者:B3Y6E,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/126714.html