无法访问 class 参数中的函数
cannot reach function in class parameter
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'))
如果您绝对必须拥有一个对象,那么我们还可以考虑做其他事情。这有帮助吗?
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'))
如果您绝对必须拥有一个对象,那么我们还可以考虑做其他事情。这有帮助吗?