类方法

到目前为止,我们所看到的对象的方法被一个类的实例所调用,然后被传递给方法的 self 参数。

类方法是不同的 - 它们被一个类所调用,类方法传递的 参数是 cls 。

类方法用 classmethod 装饰器标记。

例如:

class Rectangle:
  def __init__(self, width, height):
    self.width = width
    self.height = height

  def calculate_area(self):
    return self.width * self.height

  @classmethod
  def new_square(cls, side_length):
    return cls(side_length, side_length)

square = Rectangle.new_square(5)
print(square.calculate_area())
==========
结果:
25

new_square 是一个类方法,在类上调用,而不是在类的实例上调用。它返回类 cls 的新对象。

从技术上说,参数 self 和 cls 只是惯例; 他们可以改变为其他任何东西。然而,它们是普遍被遵循的,所以坚持使用它们是明智的。

最后修改:2022 年 12 月 05 日
如果觉得我的文章对你有用,请随意赞赏