2

I'm trying to pass a method as an argument outside of the definition of a class. However, since it's not defined in that scope, it doesn't work. Here's what I'd like to do:

def applyMethod(obj, method):
    obj.method()

class MyClass():
    def myMethod(self):
        print 1

a = MyClass()    

#works as expected
a.myMethod()

#"NameError: name 'myMethod' is not defined"
applyMethod(a, myMethod)

1 Answer 1

2

myMethod is only defined in the namespace of MyClass. Your code could look like this:

def applyMethod(obj, method):
    method(obj)

class MyClass():
    def myMethod(self):
        print 1

a = MyClass()    

a.myMethod()

applyMethod(a, MyClass.myMethod)

Now you're referencing myMethod from the namespace it exists in, and calling the equivalent of obj.myMethod() from the applyMethod function.

That's all you need - the instance.method() is just syntactic sugar for ClassName.method(instance), so I just rewrote the applyMethod function to work without the syntactic sugar, i.e. be passed in as the raw MyClass.myMethod, then gave it an instance of MyClass as its first argument. This is what the a.myMethod() syntax is doing in the backend.

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

Comments

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.