您的位置:首页 > 编程语言 > Python开发

python 动态调用模块&类&方法

2013-08-28 12:24 661 查看
转载自:/article/5084685.html

一直想知道python里有没有类似php中的 $classname->$method() 或 call_user_func

今天有时间查了一下,示例代码如下:

classname.py

1 #!/usr/bin/python
2
3 class classname:
4     def mod1(self):
5         pass
6
7     def echo(self):
8         print "test"


test.py

1 #!/usr/bin/python
2
3 def test():
4     clsname = "classname"
5     method = "echo"
6
7     obj = __import__(clsname) # import module
8     c = getattr(obj,clsname)
9     obj = c() # new class
10     #print(obj)
11     #obj.echo()
12     mtd = getattr(obj,method)
13     mtd() # call def
14
15 if __name__ == '__main__':
16    test()


?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: