下面是带有方法的测试类,这些类不使用cls或self参数,也没有@staticmethod装饰符。它们像普通的静态方法一样工作,不抱怨争论。这似乎与我对python方法的理解相反。python是否自动将非类、非实例方法视为静态方法?
>>> class Test():
... def testme(s):
... print(s)
...
>>> Test.testme('hello')
hello
>>> class Test():
... def testme():
... print('no')
...
>>> Test.testme()
noP.S:我用的是python3.4
发布于 2015-05-11 10:11:57
请注意,这在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)但是在Python3中,删除了未绑定的方法,正如Alex指出的in this answer。所以,实际上,您所做的就是调用一个在Test类中定义的普通函数。
发布于 2015-05-11 10:11:00
有点像,是的。但是,请注意,如果在实例上调用这样一个“隐式静态方法”,则会得到一个错误:
>>> 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()
nohttps://stackoverflow.com/questions/30164776
复制相似问题