Does python consider any method without cls or self arguments implicitly as static?
以下是测试类,这些类的方法不接受CLS或自变量,也没有@StaticMethod修饰符。它们像正常的静态方法一样工作,不抱怨参数。这似乎与我对Python方法的理解相反。Python是否自动将非类、非实例方法视为静态方法?
1 2 3 4 5 6 7 8 9 10 11 12 13 | >>> class Test(): ... def testme(s): ... print(s) ... >>> Test.testme('hello') hello >>> class Test(): ... def testme(): ... print('no') ... >>> Test.testme() no |
P.S:我用的是Python3.4
请注意,这在Python2中不起作用:
1 2 3 4 5 6 7 8 9 | >>> 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中,未绑定的方法被移除了,正如亚历克斯·马泰利在这个答案中指出的那样。所以实际上,您所要做的就是调用一个恰好在测试类中定义的普通函数。
有点像,是的。但是,请注意,如果在实例上调用这样的"隐式静态方法",则会得到一个错误:
1 2 3 4 5 | >>> 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 |
这是因为仍然传递
1 2 3 4 5 6 7 8 9 10 | >>> class Test: @staticmethod def testme(): print('no') >>> Test.testme() no >>> Test().testme() no |