Python对类实例使用getattr

在类的成员函数中,若是你想经过一个字符串(成员函数名)来调用类的成员函数,该怎么作?函数

class A:
    val = 1
    def __init__(self):
        pass

    def fun_1(self):
        print self.val
        print "in fun_1"

    def fun_2(self):
        print "in fun_2"

对于上面的类,你能够这样用code

obj = A()
s = 'fun_1'
fn = getattr(obj, s)
fn()

可是若是你传给getattr的第一个参数是对象名,那么就要这样用对象

obj = A()
s = 'fun_1'
fn = getattr(A, s)
fn(obj)

至关因而fn只是一个函数名,须要一个调用参数,第一个参数就是self,也就是对象实例。
在类成员函数中,能够这样用字符串

class A:
    val = 1
    def __init__(self):
        pass
    def control(self):
        name = 'fun_1'
        fn = getattr(A, name)
        fn(self)
    def fun_1(self):
        print self.val
        print "in fun_1"
    def fun_2(self):
        print "in fun_2"

看上面的成员函数control,也是同一个道理。
若是像下面这样写的话,会出错get

def control(self):
    name = 'fun_1'
    fn = getattr(A, name)
    fn()

报错信息就是
TypeError: unbound method fun_1() must be called with A instance as first argument (got nothing instead)
这个基本上指明了缘由。it

相关文章
相关标签/搜索