"""
python中的反射功能
python中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr,改四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。
"""classPerson():def__init__(self,name,age):
self.name = name
self.age = age
defwalk(self):print("walking......")defrun(self):print(f"{self.name} is running....")
p = Person("Alex",22)ifhasattr(p,'name'):print("有该成员")#获取属性
a =getattr(p,'age')print(f'{a}被获取')#获取方法
method =getattr(p,'walk')print(method)
method()#设置属性setattr(p,'sex','Female')print(p.sex)#设置方法setattr(Person,'go',run)
p.go()#删除属性delattr(p,'name')print(p.name)
结果
AttributeError:'Person'object has no attribute 'name'
有该成员
22被获取
<bound method Person.walk of <__main__.Person object at 0x0418DCD0>>
walking......
Female
Alex is running....