无法在类参数中达到功能

时间:2019-02-27 00:56:19

标签: python python-3.x eval

class Method:
    def __init__(self,command):
        eval('Method.command')
    def send_msg(self):
        return True

我期待将Trueprint(Method(send_msg))一起使用,但会引发以下错误。

NameError: name 'send_msg' is not defined

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

它就是它所说的。 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'))

如果您绝对必须有一个对象,那么我们可以考虑做其他事情。这有帮助吗?

相关问题