我尝试在下面运行此代码
class TestStaticMethod:
def foo():
print 'calling static method foo()'
foo = staticmethod(foo)
class TestClassMethod:
def foo(cls):
print 'calling class method foo()'
print 'foo() is part of class: ', cls.__name__
foo = classmethod(foo)
使用下面的代码运行后
tsm = TestStaticMethod()
TestStaticMethod.foo()
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
TestStaticMethod.foo()
TypeError: unbound method foo() must be called with TestStaticMethod instance as first argument (got nothing instead)
tsm.foo()
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
ts.foo()
TypeError: foo() takes no arguments (1 given)
我真的不明白为什么我得到了未绑定的方法。谁能帮我?
答案 0 :(得分:0)
您应通过取消foo
类<{1}}
TestStaticMethod
变量来尝试以下代码
class TestStaticMethod:
def foo():
print 'calling static method foo()'
foo = staticmethod(foo)
tsm = TestStaticMethod()
tsm.foo()
答案 1 :(得分:0)
你不应该缩进
foo = staticmethod(function_name)
在函数(foo)中,
请尝试一下:
class TestStaticMethod:
def foo():
print 'calling static method foo()'
foo = staticmethod(foo)
或
class TestStaticMethod:
@staticmethod
def foo():
print 'calling static method foo()'
以上两种解决方案都可以使用