class Method:
def __init__(self,command):
eval('Method.command')
def send_msg(self):
return True
我期待使用 print(Method(send_msg))
得到 True
,但它却引发了以下错误。
NameError: name 'send_msg' is not defined
如何解决这个问题?
最佳答案
这正是它所说的。 send_msg 本身没有任何意义。您首先需要一个 Method 对象。所以 Method(some_command).send_msg() 可以工作。这是假设您在命令有效时传入的任何内容。但 send_msg 是一个只有在拥有对象后才能访问的函数。
编辑1
我认为没有任何理由在这里使用对象。有很多不同的方法可以实现您想要的目标。我通常做的事情是这样的。
map = {}
def decorator(func):
map[func.__name__] = func
return func
@decorator
def send_msg(msg):
return True
received_input = 'send_msg'
print(map)
print(map[received_input]('a message'))
如果你绝对必须有一个对象,那么我们可以考虑做其他事情。这有帮助吗?
关于python - 无法到达类参数中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54896427/