我们真的需要在python中使用@staticmethod装饰器来声明静态方法吗? [英] Do we really need @staticmethod decorator in python to declare static method

查看:36
本文介绍了我们真的需要在python中使用@staticmethod装饰器来声明静态方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么我们需要 @staticmethod 装饰器将方法声明为 static.我正在阅读 Python 中的静态方法,我开始知道静态方法可以在不实例化其类的情况下调用.所以我尝试了下面的两个例子,但都一样:

I am curious about why we need the @staticmethod decorator to declare method as static. I was reading about static methods in Python, and I came to know that static method can be callable without instantiating its class. So I tried the two examples below, but both do the same:

class StatMethod:
  def stat():
    print("without Decorator")

class StatMethod_with_decorator:
  @staticmethod
  def stat():
    print("With Decorator")

如果我直接在类上调用 stat() 方法,都会打印/显示以下值:

If I call the stat() method on the class directly, both print/show the values below:

>> StatMethod.stat()
without Decorator
>> StatMethod_with_decorator.stat()
With Decorator

推荐答案

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

You need the decorator if you intend to try to call the @staticmethod from the instance of the class instead of of the class directly

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 参数不会作为第一个参数隐式传递

Now if I declare @staticmethod the self argument isn't passed implicitly as the first argument

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

>>> f = Foo()
>>> f.bar(4)
9

这篇关于我们真的需要在python中使用@staticmethod装饰器来声明静态方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆