反射

# 反射:通过字符串映射到对象的属性

class People:
country = 'china'

def __init__(self,name,age):
self.name=name
self.age=age


def talk(self):
print('%s is talking' % self.name)


obj = People('kingforn',28)

print(obj.name)
print(obj.talk)
print(obj.__dict__)
'''
打印结果:
kingforn
<bound method People.talk of <__main__.People object at 0x0000028089C94B38>>
{'name': 'kingforn', 'age': 28}
'''
# ----------- 通过 hasattr(obj, str) 方法 ,判断对象里面字典里的key是不是跟str同名
print(hasattr(obj,'name'))
print(hasattr(obj,'talk'))
'''
执行结果:
True
True
存在就是True,不存在就是False
'''

# -------- getattr 通过字符串获得对象属性的值 -----------
print(getattr(obj,'name')) # obj.name
print(getattr(obj,'talk')) # obj.talk
'''
执行结果:
kingforn
<bound method People.talk of <__main__.People object at 0x000002727B6C46D8>>
'''

# --------- setattr 方法是 通过字符串修改 对象属性值和创建对象属性值 -------------
print(getattr(obj,'sex','None'))
setattr(obj,'sex','female') # obj.sex = 'female'
print(getattr(obj,'sex','None'))

'''
执行结果:
None
female
'''
# --------- delattr 方法是通过字符串 删除 对象属性 --------------
print(getattr(obj,'sex','None'))
delattr(obj,'sex') # del obj.sex
print(getattr(obj,'sex','None'))

'''
执行结果是:
female
None #说明已经删除了
'''

# --------getattr,setattr,delattr 不但支持对象同样可以支持类
print(getattr(People,'country')) # People.country

# 执行结果:china

######################################
# 反射的应用

class Service:
def run(self):
while True:
inp = input('>>>:').strip()
cmds = inp.split()
if hasattr(self,cmds[0]):
func=getattr(self,cmds[0])
func(cmds[1])

def get(self,rags):
print('get ............. %s'%rags)


def put(self,rags):
print('put ............. %s'%rags)



r1 = Service()
r1.run()
'''
>>>:xxx
>>>:xxx
>>>:yyyy
>>>:get a.txt
get ............. a.txt
>>>:put a.txt
put ............. a.txt
>>>:
'''
原文地址:https://www.cnblogs.com/kingforn/p/11346314.html