Python - classmethod() 函式



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

示例:修改類狀態或靜態資料

@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
python_built_in_functions.htm
廣告