How to find a function of a class by its name in python?
Question:
I mean , for example, in the following code I want to call prin in pre by name, but how?
class a(object):
def __init__(self):
self.zz=1
self.aa='hello'
def prin(self):
print 'hello'
def pre(self,name):
#if name is 'prin' then call self.prin
if __name__ == '__main__':
az = a()
az.pre('prin')`
Answers:
getattr
def pre(self,name):
# name being 'prin' in your case
if hasattr(self, name):
getattr(self, name)()
I mean , for example, in the following code I want to call prin in pre by name, but how?
class a(object):
def __init__(self):
self.zz=1
self.aa='hello'
def prin(self):
print 'hello'
def pre(self,name):
#if name is 'prin' then call self.prin
if __name__ == '__main__':
az = a()
az.pre('prin')`
getattr
def pre(self,name):
# name being 'prin' in your case
if hasattr(self, name):
getattr(self, name)()