【问题标题】:Does python consider any method without cls or self arguments implicitly as static?python 是否将任何没有 cls 或 self 参数的方法隐含地视为静态?
【发布时间】:2015-07-21 18:52:45
【问题描述】:

以下是测试类,其方法不接受 cls 或 self 参数,并且没有 @staticmethod 装饰器。它们像普通的静态方法一样工作,不会抱怨参数。这似乎与我对 python 方法的理解相反。 python是否会自动将非类、非实例方法视为静态方法?

>>> class Test():
... def testme(s):
...  print(s)
...
>>> Test.testme('hello')
hello

>>> class Test():
...  def testme():
...   print('no')
...
>>> Test.testme()
no

P.S:我用的是python3.4

【问题讨论】:

标签: python python-3.x


【解决方案1】:

请注意,这在 Python 2 中不起作用:

>>> class Test(object):
...     def testme():
...         print 'no'
...
>>> Test.testme()
Traceback (most recent call last):
  File "<ipython-input-74-09d78063da08>", line 1, in <module>
    Test.testme()
TypeError: unbound method testme() must be called with Test instance as first argument (got nothing instead)

但在 Python 3 中,未绑定的方法已被移除,正如 Alex Martelli 指出的 in this answer。所以实际上你所做的只是调用一个恰好在 Test 类中定义的普通函数。

【讨论】:

    【解决方案2】:

    有点确实如此,是的。但是请注意,如果你在一个实例上调用这样一个“隐式静态方法”,你会得到一个错误:

    >>> Test().testme()
    Traceback (most recent call last):
      File "<pyshell#2>", line 1, in <module>
        Test().testme()
    TypeError: testme() takes 0 positional arguments but 1 was given
    

    这是因为self 参数仍然被传递,而正确的@staticmethod 不会发生这种情况:

    >>> class Test:
        @staticmethod
        def testme():
            print('no')
    
    
    >>> Test.testme()
    no
    >>> Test().testme()
    no
    

    【讨论】:

    • 虽然与这里的问题和答案间接相关,但有一个有趣的answer@staticmethod@classmethod 的行为方式。
    猜你喜欢
    • 2020-03-03
    • 2014-03-28
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2017-09-01
    • 2019-05-20
    • 2015-07-14
    • 1970-01-01
    相关资源
    最近更新 更多