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?

3
  • 1
    send_msg is not defined... Define it. But really, what you are trying to do here is almost certainly not the right way of doing things. Commented Feb 27, 2019 at 0:58
  • Agree with @juanpa.arrivillaga, also using is not a good practice stackoverflow.com/a/1832957/10587443 Commented Feb 27, 2019 at 1:00
  • I just want to keep the syntax and figure out a way to call a Method with the method_name in parameter. Method(doSomething) Commented Feb 27, 2019 at 1:00

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

8 Comments

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?
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?
I'm trying to detect an input and according to that I want to call a specific function, as if bot commands
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
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.