1. 程式人生 > >動態呼叫Python的函式,物件方法以及屬性

動態呼叫Python的函式,物件方法以及屬性

def do_foo():
    print "foo!"

def do_bar():
    print "bar!"

class Print():
    def __init__(self):
        self.x = 1;
    def do_foo(self):
        print "foo!"

    def do_bar(self):
        print "bar!"

    def foo(self):
        print("foo")

    @staticmethod
    def static_foo():
        print
"static foo!" @staticmethod def static_bar(): print "static bar!" if __name__ == '__main__': obj = Print() func_name = "do_foo" static_name = "static_foo" fun="foo" x = "x" eval(func_name)() print(getattr(obj, x)) getattr(obj, fun)() getattr(Print, static_name)() func_name = "do_bar"
static_name = "static_bar" eval(func_name)() getattr(obj, func_name)() getattr(Print, static_name)()

其核心就是eval和getattr這兩個函式