1
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?

1 Answers1

1

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?

bravosierra99
  • 1,331
  • 11
  • 23
  • `send_msg is a function that will only ever be accessible once you have an object` is this statement really true? Isn't there any way to call my function in a parameter? – libensvivit Feb 27 '19 at 01:07
  • what are you actually trying to accomplish? whatever you are trying to do, does not really make sense in python. Could you give a use case? perhaps we could help you understand the pythonic way to accomplish that? – bravosierra99 Feb 27 '19 at 01:20
  • I'm trying to detect an input and according to that I want to call a specific function, as if bot commands – libensvivit Feb 27 '19 at 01:24
  • That is not strictly true. You can access the function object itself just fine. It's just *normally* it would be accessed as a method on an instance of class `Method` – juanpa.arrivillaga Feb 27 '19 at 01:25
  • @juanpa.arrivillaga fairly certain what you said is false. Can you please provide some documentation? – bravosierra99 Feb 27 '19 at 01:44
  • Just consider: `send_msg = Method.send_msg; print(send_msg(None))` No objects of type `Method` involved. – juanpa.arrivillaga Feb 27 '19 at 01:49
  • @juanpa.arrivillaga interesting, thanks for sharing. Thought you could only do that with static or class methods. – bravosierra99 Feb 27 '19 at 01:51
  • 1
    No, a *method* in Python is merely a normal function that *is an attribute to a class*. It doesn't even have to be defined in the class. What is "special" about this situation is that it "magically" gets passed the instance when called via an instance of the class it is a member of. But if accessed on the class, it is just the plain object. – juanpa.arrivillaga Feb 27 '19 at 01:53