可能重复:
What is the difference between @staticmethod and @classmethod in Python?
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?
- 哪些方案适合使用这些方法中的每一种?
答案 0 :(得分:5)
classmethod传递了调用它的类'cls'。有关详细信息,请参阅:What is the difference between @staticmethod and @classmethod in Python?