If I have an object and a method name in a string, how can I call the method?
class Foo:
def bar1(self):
print 1
def bar2(self):
print 2
def callMethod(o, name):
???
f = Foo()
callMethod(f, "bar1")
If I have an object and a method name in a string, how can I call the method?
class Foo:
def bar1(self):
print 1
def bar2(self):
print 2
def callMethod(o, name):
???
f = Foo()
callMethod(f, "bar1")
Easy one:
class Foo:
def bar1(self):
print 1
def bar2(self):
print 2
def callMethod(o, name):
getattr(o, name)()
f = Foo()
callMethod(f, "bar1")
Take a look at getattr
You can also use setattr for setting Class attributes by names.
getattr(globals()['Foo'](), 'bar1')()
getattr(globals()['Foo'](), 'bar2')()
No need to instantiate Foo first!
def callmethod(cls, mtd_name):
method = getattr(cls, mtd_name)
method()