为什么在下面的代码中,使用类变量作为方法指针会导致未绑定(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/