python - 指向 Python 中静态方法的指针

标签 python function-pointers static-methods

为什么在下面的代码中,使用类变量作为方法指针会导致未绑定(bind)方法错误,而使用普通变量却可以:

class Cmd: 
    cmd = None

    @staticmethod   
    def cmdOne():
        print 'cmd one'

    @staticmethod   
    def cmdTwo():
        print 'cmd two'

def main():
    cmd = Cmd.cmdOne
    cmd() # works fine

    Cmd.cmd = Cmd.cmdOne        
    Cmd.cmd() # unbound error !!

if __name__=="__main__":
    main()

完整错误:

TypeError: unbound method cmdOne() must be called with Cmd instance as 
           first argument (got nothing instead)

最佳答案

需要使用staticmethod()来转换函数:

Cmd.cmd = staticmethod(Cmd.cmdOne)

关于python - 指向 Python 中静态方法的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16229691/

相关文章:

python - 我如何实现具有多个 init 继承的 super() ?

c++ - 在没有上下文参数的情况下将有状态 lambda 传递给 C 样式函数

c++ - 可变参数模板函数确定函数指针返回类型

c++ - 是否可以获取 ADL 函数的地址?

c# - 在 Web 应用程序 (.net) 中使用静态方法是否存在潜在缺陷?

python |列表理解|多重标准

python - 通过对单元格进行分组在 pandas 列上绘制直方图

python - 如何用一个线程监听redis的所有订阅 channel ?

java - java接口(interface)中的静态方法

c# - 使用 Moq 模拟异步静态方法