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)
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments