您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

我们是否真的需要python中的@staticmethod装饰器来声明静态方法

我们是否真的需要python中的@staticmethod装饰器来声明静态方法

如果您打算尝试@staticmethod从类的实例而不是直接从类的实例调用,则需要装饰器

class Foo():
    def bar(x):
        return x + 5

>>> f = Foo()
>>> f.bar(4)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    f.bar(4)
TypeError: bar() takes 1 positional argument but 2 were given

现在,如果我宣布@staticmethodself参数不隐式传递作为第一个参数

class Foo():
    @staticmethod
    def bar(x):
        return x + 5

>>> f = Foo()
>>> f.bar(4)
9
python 2022/1/1 18:51:25 有369人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶