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

9
可能重复:
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

我认为类方法更加灵活,因为我们不需要硬编码类名。

问题:
- 哪个更好的问题甚至不存在?@staticmethod还是@classmethod?
- 每种方法适用的场景是什么?


1
dup https://dev59.com/l3VC5IYBdhLWcg3w9GHM - Sid
1
我要问的问题不是哪个更好,而是哪个更适合你所处的特定情况。 - alexis
1个回答

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接