'''
1、什么是反射
通过字符串来操作类或者对象的属性
2、如何用
hasattr
getattr
setattr
delattr
'''
class People:
country='China'
def __init__(self,name):
self.name=name
def eat(self):
print('%s is eating' %self.name)
peo1=People('egon')
# print(hasattr(peo1,'eat')) #peo1.eat
# print(getattr(peo1,'eat')) #peo1.eat
# print(getattr(peo1,'xxxxx',None))
# setattr(peo1,'age',18) #peo1.age=18
# print(peo1.age)
# print(peo1.__dict__)
# delattr(peo1,'name') #del peo1.name
# print(peo1.__dict__)
class Ftp:
def __init__(self,ip,port):
self.ip=ip
self.port=port
def get(self):
print('GET function')
def put(self):
print('PUT function')
def run(self):
while True:
choice=input('>>>: ').strip()
# print(choice,type(choice))
# if hasattr(self,choice):
# method=getattr(self,choice)
# method()
# else:
# print('输入的命令不存在')
method=getattr(self,choice,None)
if method is None:
print('输入的命令不存在')
else:
method()
conn=Ftp('1.1.1.1',23)
conn.run()
#__getattr__拦截点号运算。当对未定义的属性名称和实例进行点号运算时,就会用属性名作为字符串调用和这个方法。
# 如果继承可以找到该属性,则不调用此方法
#__setattr__会拦截所有属性的赋值语句。如果定义了这个方法,self.arrt = value 就会编程self,__setattr__("attr",value)
# 这个需要注意。当在__setattr__方法内对属性进行赋值时,是不可使用slef.attr=value,因为他会再次调用
# self,__setattr__("attr",value),则会形成无穷递归循环,最后导致堆栈溢出异常,应该通过对属性字典做索引运算来赋值任何实例属性,也就是使用self.__dict__{"name"}=value