Python - 类方法
方法 属于类的一个对象,用于执行特定操作。我们可以将 Python 方法分为三种不同的类别,即 class method、instance method 和 static method。
Python 的 类方法 是一种绑定到类而不是类实例的方法。它可以在类本身上调用,而不是在类的实例上调用。
我们大多数人经常将类方法与静态方法混淆。请始终记住,虽然两者都是在类上调用,但 静态方法 无法访问 "cls" 参数,因此不能修改类状态。
与类方法不同,实例方法 可以访问对象的实例变量。它也可以访问类变量,因为类变量对所有对象都是通用的。
在 Python 中创建类方法
在 Python 中创建类方法有两种方式 −
- 使用 classmethod() 函数
- 使用 @classmethod 装饰器
使用 classmethod() 函数
Python 有一个内置函数 classmethod(),它将实例方法转换为 类方法,该类方法只能通过类的引用调用,而不能通过对象调用。
语法
classmethod(instance_method)
示例
在 Employee 类中,定义一个带有 "self" 参数(调用对象的引用)的 showcount() 实例方法。它打印 empCount 的值。接下来,将该方法转换为可以通过类引用访问的类方法 counter()。
class Employee:
empCount = 0
def __init__(self, name, age):
self.__name = name
self.__age = age
Employee.empCount += 1
def showcount(self):
print (self.empCount)
counter = classmethod(showcount)
e1 = Employee("Bhavana", 24)
e2 = Employee("Rajesh", 26)
e3 = Employee("John", 27)
e1.showcount()
Employee.counter()
输出
使用对象调用 showcount(),使用类调用 counter(),两者都会显示员工计数的数值。
3 3
使用 @classmethod 装饰器
使用 @classmethod() 装饰器是定义类方法的推荐方式,因为它比先声明实例方法然后将其转换为类方法更方便。
语法
@classmethod def method_name(): # 你的代码
示例
类方法可以作为备选构造函数。定义一个 newemployee() 类方法,带有构造新对象所需的参数。它返回构造的对象,这与 __init__() 方法的作用相同。
class Employee:
empCount = 0
def __init__(self, name, age):
self.name = name
self.age = age
Employee.empCount += 1
@classmethod
def showcount(cls):
print (cls.empCount)
@classmethod
def newemployee(cls, name, age):
return cls(name, age)
e1 = Employee("Bhavana", 24)
e2 = Employee("Rajesh", 26)
e3 = Employee("John", 27)
e4 = Employee.newemployee("Anil", 21)
Employee.showcount()
现在有四个 Employee 对象。如果运行上述程序,它将显示 Employee 对象的计数 −
4
在类方法中访问类属性
类属性 是属于类的变量,其值在该类的所有实例之间共享。
要在类方法中访问类属性,使用 cls 参数,后跟点 (.) 符号和属性的名称。
示例
在这个示例中,我们在类方法中访问类属性。
class Cloth:
# 类属性
price = 4000
@classmethod
def showPrice(cls):
return cls.price
# 访问类属性
print(Cloth.showPrice())
运行上述代码,将显示以下输出 −
4000
动态向类添加类方法
Python 的 setattr() 函数用于动态设置属性。如果要向类添加类方法,可以将方法名作为参数值传递给 setattr() 函数。
示例
以下示例展示了如何动态向 Python 类添加类方法。
class Cloth:
pass
# class method
@classmethod
def brandName(cls):
print("Name of the brand is Raymond") # 类方法
# 动态添加
setattr(Cloth, "brand_name", brandName)
newObj = Cloth()
newObj.brand_name()
执行上述代码时,将显示以下输出 −
Name of the brand is Raymond
动态删除类方法
Python 的 del 操作符用于动态删除类方法。如果尝试访问已删除的方法,代码将引发 AttributeError。
示例
在下面的示例中,我们使用 del 操作符删除名为 "brandName" 的类方法。
class Cloth:
# class method
@classmethod
def brandName(cls):
print("Name of the brand is Raymond") # 类方法
# 动态删除
del Cloth.brandName
print("Method deleted") # 方法已删除
执行上述代码时,将显示以下输出 −
Method deleted