反射

#通过字符串映射到对象的属性
class People:
county = 'china'
def __init__(self, name, age):
self.name = name
self.age = age
def take(self):
print('%s is taking'%self.name)
p = People('alex', 18)
print(p.name)#打印name属性
print(p.take)#打印绑定的方法

# chice = input('>>>') #chice = 'name'
# print(p.chice) #print(chice.''name'')
#查询属性 结果为True或者False
print(hasattr(p, 'name')) #判断有没有''name''这个属性,结果返回True或者False
print(hasattr(p, 'take')) #判断有没有''take''这个函数属性,结果返回True或者False
#查询属性,返回属性的值
print(type(getattr(p, 'name', None))) #把字符串'''name'''当做属性name查询到属性name的值,如果没有name这个属性则返回None,前提是''name''后要加None参数
print(getattr(p, 'take', None)) #查到一个绑定方法
#设置增加修改属性,(以字符串形式)
setattr(p, 'sex', 'male') #通过字符串形式添加设置新的属性
print(p.sex) #打印通过字符串添加的属性
#删除属性,(以字符串形式)
delattr(p, 'age')
print(p.__dict__)
#同时以上四种方法不光可以用于对象还可以用于类
print(getattr(People, 'county'))




#反射的应用场景
class Serive:
def run(self):
while 1:
inp = input('>>>').strip() #get, a.txt
cmds = inp.split(',') #[get, a.txtx]
print(cmds)
if hasattr(self, cmds[0]): #以字符串的get判断是否有get属性
#print(getattr(self, cmds[0]))
func = getattr(self, cmds[0])#查询字符串get属性并且赋值,此时字符串get等于函数get
func(cmds) #调用get方法
def get(self, cmds):
print('get...')
def put(self, cmds):
print('put...')
s = Serive()
s.run()

posted on 2019-01-12 11:46  别离  阅读(78)  评论(0编辑  收藏  举报

导航