Python classmethod() 函数将实例方法转换为类方法。此函数允许我们在给定类中调用方法,而无需创建其实例。
classmethod() 是 @classmethod 装饰器的替代方案,它指定给定的方法属于该类。它通常用于工厂方法,这些方法返回类的实例。
classmethod() 函数是内置函数之一,不需要导入任何模块。
语法
Python classmethod() 的语法如下所示 -
classmethod(instance_method)
参数
Python classmethod() 函数接受单个参数 -
- instance_method − 它表示实例方法。
返回值
Python classmethod() 函数返回属于类的方法。
classmethod() 函数示例
练习以下示例来理解 Python 中 classmethod() 函数的使用:
示例:使用 classmethod() 函数创建工厂方法
如前所述,classmethod() 可以创建为不同用例返回类对象的工厂方法。在这里,我们创建了两个名为 “motorcycle()” 和 “car()” 的工厂方法,然后使用它们来创建不同类型的车辆。
class Vehicle:
def __init__(self, wheels, seats):
self.wheels = wheels
self.seats = seats
def motorcycle(cls):
return cls(2, 2)
def car(cls):
return cls(4, 5)
# Converting instance method to class method
Vehicle.motorcycle = classmethod(motorcycle)
Vehicle.car = classmethod(car)
heroBike = Vehicle.motorcycle()
tataCar = Vehicle.car()
#printing the details
print("Bike details - ")
print(f"Wheels: {heroBike.wheels}, Seat Capacity: {heroBike.seats}")
print("Tata Car Details - ")
print(f"Wheels: {tataCar.wheels}, Seat Capacity: {tataCar.seats}")
当我们运行上述程序时,它会产生以下结果——
Bike details -
Wheels: 2, Seat Capacity: 2
Tata Car Details -
Wheels: 4, Seat Capacity: 5
Wheels: 2, Seat Capacity: 2
Tata Car Details -
Wheels: 4, Seat Capacity: 5
示例:修改类状态或静态数据
@classmethod 装饰器还可用于修改类状态或静态数据。在此示例中,我们定义了一个变量,然后使用装饰器修改其值。这个装饰器是指定类方法的另一种方式。
class Laptop:
os = "windows"
@classmethod
def newOs(cls):
cls.os = "iOS"
print(f"Previous operating system: {Laptop.os}")
# Changing the class attribute
Laptop.newOs()
print(f"New operating system: {Laptop.os}")
上述代码的输出如下 -
Previous operating system: windows
New operating system: iOS
New operating system: iOS