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')`
Asked By: Crazymage

||

Answers:

getattr

def pre(self,name):
    # name being 'prin' in your case
    if hasattr(self, name):
        getattr(self, name)()
Answered By: Brian
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.