1. 什么是反射?
反射就是通过字符串来操作类或对象的属性
2 .反射的方式由四种:hasattr 、 getattr 、 setattr 、 delattr
hasattr(obj,attrib) 判断对象是否存在这个属性,存在就返回True
getattr(obj,attrib,None) 判断属性对象是否可以访问,如果可以就返回数据属性的值,函数属性的内存地址。如果不能,就返会None。
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(hasattr(peo1,'name')) #peo1.eat
print(getattr(peo1,'eat')) #peo1.eat
print(getattr(peo1,'name')) #peo1.eat
print(getattr(peo1,'xxxxx',None))
# 结果如下:
# True
# True
# <bound method People.eat of <__main__.People object at 0x00000205888894E0>>
# egon
# None
setattr(obj,attrib,属性值) 修改对象的属性值,如果没有该属性则添加属性到名称空间
delattr(obj,attrib) 删除对象名称空间里的属性值,删除类的属性值,数据属性和函数属性都可以删除
class People:
country='China'
def __init__(self,name):
self.name=name
def eat(self):
self.name = "alex" # 在方法内部也可以修改属性值,修改的属性值存在名称空间中
print('%s is eating' %self.name)
def sleep(self):
print("%s is sleeping"%self.name)
peo1=People('egon')
setattr(peo1,'age',18) #peo1.age=18
print(peo1.age)
print(peo1.__dict__)
peo1.eat()
print(peo1.__dict__)
print(People.__dict__)
peo1.sleep()
delattr(People,'eat') #del peo1.name
print(People.__dict__) # 删除类的属性值
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()