获取未绑定方法错误?

2024-10-03 02:44:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在下面运行这个代码

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)

我真的不明白为什么要使用unbound方法。有人能帮我吗?你知道吗


Tags: mostfoodefcallmethodclassfilecls
2条回答

您应该通过从类TestStaticMethod中删除foo变量来尝试下面的代码

class TestStaticMethod:
    def foo():
        print 'calling static method foo()'
    foo = staticmethod(foo)


tsm = TestStaticMethod()
tsm.foo()

你不应该缩进

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()'

以上两种解决方案都能奏效

相关问题 更多 >