以下是测试类,其方法没有接受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
答案 0 :(得分: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
答案 1 :(得分:2)
请注意,这在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类中定义的普通函数。