Search code examples
pythonpython-3.xeval

cannot reach function in class parameter


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

I am looking forward to get True with print(Method(send_msg)) but instead it raises the following error.

NameError: name 'send_msg' is not defined

How can I resolve this problem?


Solution

  • it's exactly what it says. send_msg by itself has no meaning. You need a Method object first. So Method(some_command).send_msg() would work. This is assuming whatever you pass in as the command works. but send_msg is a function that will only ever be accessible once you have an object.

    Edit 1

    I don't see any reason to use an object here. There are a lot of different ways to accomplish what you want. What I usually do is something like this.

    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'))
    

    If you absolutely must have an object, then there are other things we could look at doing. Does this help?