Python 类方法装饰器 @classmethod
2023-09-17 22:17:51
在 Python 中,@classmethod
装饰器用于将类中的方法声明为可以使用 ClassName.MethodName()
调用的类方法。
也可以使用类的对象调用类方法。
@classmethod
是classmethod()功能的替代方法。建议使用 @classmethod
装饰器而不是函数,因为它只是一个语法糖。
@classmethod特性(@classmethod Characteristics)
- 声明一个类方法。
- 第一个参数必须是
cls
,可用于访问类属性。
类 - 方法只能访问类属性,而不能访问实例属性。
- 可以使用
ClassName.MethodName()
调用类方法,也可以使用对象调用类方法。 - 它可以返回类的对象。
下面的示例声明一个类方法。
示例: @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.tostring() #Student Class Attributes: name=unknown
上面,Student
类包含一个类属性name
和一个实例属性age
。
tostring()
方法使用@classmethod
装饰器进行装饰,使其成为类方法,可以使用Student.tostring()
调用。
可以按classname.method()
调用类方法,也可以使用类对象object.method()
调用类方法。
注: 任何类方法的第一个参数都必须cls
可用于访问类的属性。您可以为第一个参数指定任何名称,而不是 cls
。
类方法只能访问类属性,而不能访问实例属性。如果尝试访问类方法中的实例属性,则会引发错误。
示例: @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)
Student.tostring() #calling class method
类方法也可以用作工厂方法来获取类的对象,如下所示。
示例: @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)
std = Student.getobject()
print(std.name) #'Steve'
print(std.age) #25
@classmethod vs @staticmethod
下表列出了类方法和static method之间的区别:
@classmethod | @staticmethod |
---|---|
声明一个类方法。 | 声明静态方法。 |
它可以访问类属性,但不能访问实例属性。 | 它无法访问类属性或实例属性。 |
可以使用ClassName.MethodName() 或object.MethodName() 调用它。 | 可以使用ClassName.MethodName() 或object.MethodName() 调用它。 |
它可用于声明返回类对象的工厂方法。 | 它不能返回类的对象。 |
本文内容总结: