Python:静态方法与类方法的区别

day*_*mer 6 python oop

可能重复:
Python中@staticmethod和@classmethod有什么区别?

  • 我在python中学习OOP,并开始了解这两种方法
  • 似乎语法方面的差异是类方法隐式地将它们所属的类作为它们的第一个参数传递
class Circle:
  all_circles = [] # class variable

  @staticmethod
  def total_area():
      for c in Circle.all_circles: # hardcode class name
          # do somethig

  @classmethod
  def total_area(cls):
      for c in cls.all_circles: # no hardcode class name
          # do something
Run Code Online (Sandbox Code Playgroud)

我认为类方法更灵活,因为我们不对类进行硬编码

问题:
- 这是一个更好的问题吗?@staticmethod还是@classmethod?
- 哪些方案适合使用这些方法中的每一种?

Sid*_*Sid 5

classmethod传递了它被调用的类'cls'.有关更多详细信息,请参阅:Python中的@staticmethod和@classmethod有什么区别?