Reputation: 435
Well I am trying to do this:
class Foo(object):
def method1(self):
print "method1"
def method2(self):
print "method2"
class Fo1(object):
def __init__(self):
self.a = Foo()
def classMethod(self, selection):
self.a.selection()
A = Fo1()
A.classified('method2')
I got this error:
--> AttributeError: 'Fo1' object has no attribute 'selection'
I don't want to use this (seems to me, more coding):
def classified(self,selection):
if selection == "method1": self.a.method1()
elif selection == "method2": self.a.method2()
How should I code the method so that I can pass the method name as an argument? Thanks!
Upvotes: 0
Views: 451
Reputation: 55933
You can use getattr
to do this, e.g.
def classMethod(self, selection):
getattr(self.a, selection)()
getattr takes an object an attribute name and returns the attribute, which you can then call.
Upvotes: 4