如何在python中通过名称查找类的函数?

时间:2015-10-17 02:44:28

标签: python

我的意思是,例如,在下面的代码中,我想通过名称调用prin,但是如何?

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')`

1 个答案:

答案 0 :(得分:0)

getattr

def pre(self,name):
    # name being 'prin' in your case
    if hasattr(self, name):
        getattr(self, name)()