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


一直想知道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() 

 

/usr/bin/python test.py

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM