【发布时间】: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?
- 每种方法适合使用哪些场景?
【问题讨论】:
-
我要问的问题不是哪一个更好,而是哪一个更合适——适合您所处的特定情况。