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

How to find a function of a class by its name in python?

本问题已经有最佳答案,请猛点这里访问。

我的意思是,例如,在下面的代码中,我想用pre-by-name调用prin,但是如何调用呢?

class a(object):

def __init__(self):

1
2
3
4
5
6
7
8
9
10
11
    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__':

1
2
3
az = a()

az.pre('prin')`

getattr

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