方法属于类的对象,用于执行特定操作。我们可以将 Python 方法分为三个不同的类别,分别是类方法、实例方法和静态方法。
Python 类方法是绑定到类而不是类实例的方法。它可以在类本身上调用,而不是在类的实例上调用。
我们大多数人经常将类方法与静态方法混淆。请始终记住,虽然两者都是在类上调用的,但静态方法无权访问 “cls” 参数,因此它无法修改类状态。
与 class method 不同,instance 方法可以访问 an 对象的 instance 变量。它还可以访问 class 变量,因为它对所有对象都是通用的。
在 Python 中创建类方法
在 Python 中创建类方法有两种 -
- 使用 classmethod() 函数
- 使用 @classmethod Decorator
使用 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()
输出
使用 object 调用 showcount() 和使用 class 调用 count(),两者都显示 employee count 的值。
3
使用 @classmethod Decorator
使用 @classmethod() 装饰器是定义类方法的规定方法,因为它比先声明一个实例方法,然后将其转换为类方法更方便。
语法
@classmethod
def method_name():
# your code
例
类方法充当备用构造函数。使用构造新对象所需的参数定义 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 对象的计数 -
在 Class Method 中访问类属性
类属性是属于某个类的那些变量,其值在该类的所有实例之间共享。
要在类方法中访问类属性,请使用 cls 参数,后跟点 (.) 表示法和属性名称。
例在此示例中,我们正在访问 class method 中的 class 属性。
class Cloth:
# Class attribute
price = 4000
@classmethod
def showPrice(cls):
return cls.price
# Accessing class attribute
print(Cloth.showPrice())
在运行上述代码时,它将显示以下输出 -
将类方法动态添加到类
Python setattr() 函数用于动态设置属性。如果要向类中添加类方法,请将方法名称作为参数值传递给 setattr() 函数。
例以下示例演示如何将类方法动态添加到 Python 类。
class Cloth:
pass
# class method
@classmethod
def brandName(cls):
print("Name of the brand is Raymond")
# adding dynamically
setattr(Cloth, "brand_name", brandName)
newObj = Cloth()
newObj.brand_name()
当我们执行上述代码时,它将显示以下输出 -
动态删除类方法
Python del 运算符用于动态删除类方法。如果尝试访问 deleted 方法,代码将引发 AttributeError。
例在下面的示例中,我们使用 del 运算符删除名为 “brandName” 的类方法。
class Cloth:
# class method
@classmethod
def brandName(cls):
print("Name of the brand is Raymond")
# deleting dynamically
del Cloth.brandName
print("Method deleted")
在执行上述代码时,它将显示以下输出 -