但行好事,莫问前程

挖了太多坑,一点点填回来

根据字符串名称动态调用Python的函数和对象方法

magic, php, python

在PHP里,根据字符串动态调用方法是一件很简单的事情。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Foo {
    // static method
    public static function sbar() {
        echo "foosbar!";
    }

    // normal method
    public function bar() {
        echo "foobar!";
    }
}

// normal function
function bar() {
    echo "bar!";
}

$name = "bar";
$sname = "sbar";

$name();

$foo = new Foo();
$foo->{$name}();
$foo::$sname();

输出结果:

bar!
foobar!
foosbar!

而在Python中,没有PHP中这么简单,需要一点小技巧才能实现。也许这就是没有$的坏处吧,有钱确实就是不一样,呵呵。

(example.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/python
#coding: UTF-8
"""
@author: CaiKnife

根据函数名称动态调用
"""

# normal function
def do_foo():
    print "foo!"

class Print():
    # normal method
    def do_foo(self):
        print "foo!"

    # static method
    @staticmethod
    def static_foo():
        print "static foo!"

def main():
    obj = Print()

    func_name = "do_foo"
    static_name = "static_foo"

    # use eval() to get the string value from a variable
    eval(func_name)()

    # use getattr() to get method from a class or an instance
    # sometimes you have to use is_callable() to make sure that it is a method but not an attr
    getattr(obj, func_name)()
    getattr(Print, static_name)()


if __name__ == '__main__':
    main()

输出结果:

foo!
foo!
static foo!

有点儿意思~~~

Have a nice day!