【问题标题】:Python : Difference between static methods vs class method [duplicate]Python:静态方法与类方法之间的区别[重复]
【发布时间】:2012-04-02 09:45:45
【问题描述】:

可能重复:
What is the difference between @staticmethod and @classmethod in Python?

  • 我正在学习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?
- 每种方法适合使用哪些场景?

【问题讨论】:

标签: python oop


【解决方案1】:

一个类方法被传递给它被调用的类'cls'。更多详情见:What is the difference between @staticmethod and @classmethod in Python?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多