反射:
可以结合工厂模式一起学习!
#!/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
输入你想要调用的方法:
相关知识点:
转载于:https://blog.51cto.com/lvnian/1847044