反射:通过字符串来访问到所对应的值(反射到真实的属性上)。
eg:
1 class Foo: 2 x=1 3 def __init__(self,name): 4 self.name=name 5 6 def f1(self): 7 print(‘from f1‘) 8 9 10 # print(Foo.x) #Foo.__dict__[‘x‘] 11 12 f=Foo(‘egon‘) 13 # print(f.__dict__) 14 # 15 # #1: 16 # print(f.name) 17 18 #2: 19 # print(f.__dict__[‘name‘]) 20 21 #hasattr 22 #反射到字典所对应的值 23 # print(hasattr(f,‘name‘)) #f.name 24 # print(hasattr(f,‘f1‘)) #f.f1 25 # print(hasattr(f,‘x‘)) #f.x 26 27 28 #setattr 29 #设置某个属性 30 # setattr(f,‘age‘,18)#f.age=18 31 32 #getattr 33 #得到某个属性的值 34 # print(getattr(f,‘name‘))#f.name 35 # print(getattr(f,‘abc‘,None))#f.abc 36 # print(getattr(f,‘name‘,None))#f.abc 37 38 # func=getattr(f,‘f1‘)#f.f1 39 # print(func) 40 # func() 41 # 42 43 #delattr 44 #删除某个属性的值 45 # delattr(f,‘name‘)# del f.name 46 # print(f.__dict__)
定义某个功能,输入某条命令,打印下面的功能:
class Ftpserver: def __init__(self,host,port): self.host=host self.port=port def run(self): while True: cmd=input(‘>>: ‘).strip() if not cmd:continue if hasattr(self,cmd): func=getattr(self,cmd) func() def get(self): print(‘get func‘) def put(self): print(‘put func‘)
时间: 2024-10-10 21:48:38