反射中设计到两个内置函数 hasattr和getattr
hasattr:用于判断对象是否包含对应的属性。
getattr:用于返回一个对象属性值。
class Service:
def run(self):
while True:
inp=input('>>: ').strip() #cmd='get a.txt'
cmds=inp.split() #cmds=['get','a.txt']
#print(cmds)
if hasattr(self,cmds[0]):
func=getattr(self,cmds[0])
func(cmds)
def get(self,cmds):
print('这是get func',cmds)
def put(self,cmds):
print('这是 put func.......',cmds)
obj=Service()
obj.run()
网友评论