【问题标题】:How to find a function of a class by its name in python? [duplicate]如何在python中通过名称查找类的函数? [复制]
【发布时间】:2016-01-15 21:32:11
【问题描述】:

我的意思是,例如,在下面的代码中,我想在 pre 中按名称调用 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')`

【问题讨论】:

    标签: python


    【解决方案1】:

    getattr

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      相关资源
      最近更新 更多