python 動態調用模塊&類&方法

轉載自:http://www.cnblogs.com/bluefrog/archive/2012/05/11/2496439.htmlphp

一直想知道python裏有沒有相似php中的 $classname->$method() 或 call_user_funchtml

今天有時間查了一下,示例代碼以下:python

classname.pyspa

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

test.pycode

複製代碼
 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() 
複製代碼

 

?
/ usr / bin / python test.py
相關文章
相關標籤/搜索