标签:python 反射
反射:
可以结合工厂模式一起学习!
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = ‘gaogd‘ ‘‘‘ 反射 ‘‘‘ class Myclass(object): name = ‘test‘ def sayhi(self): print " sayhi" def info(self): pass def run(): print "runing outside the class" m = Myclass() user_input = ‘test‘ ‘‘‘ if user_input == ‘sayhi‘: m.sayhi() ‘‘‘ if hasattr(m,user_input): func = getattr(m,user_input) func() else: print ‘user input not exist: ‘,user_input setattr(m,user_input,run) f = getattr(m,user_input) f() print ‘run test.but call run‘,m.test() #print m.__dict__
反射实例2:
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = ‘gaogd‘ ‘‘‘ 反射 ‘‘‘ class Myclass(object): name = ‘test‘ def sayhi(self): print " sayhi" def sayhello(self): print " sayhello" def sayno(self): print " sayno" def sayyes(self): print " yes" def put_say(self,say): if hasattr(m,say): func = getattr(m,say) func() else: print ‘user input not exist: ‘, say m = Myclass() while True: user_input = raw_input(u"输入你想要调用的方法: ") m.put_say(user_input)
输入你想要调用的方法: sayno sayno 输入你想要调用的方法: sayyes yes 输入你想要调用的方法: sayhi sayhi 输入你想要调用的方法: nosay user input not exist: nosay 输入你想要调用的方法:
相关知识点:
本文出自 “奋斗吧” 博客,转载请与作者联系!
标签:python 反射
原文地址:http://lvnian.blog.51cto.com/7155281/1847044