其他分享
首页 > 其他分享> > hasattr、getattr、setattr反射

hasattr、getattr、setattr反射

作者:互联网

首先需要知道他们都是由对象obj来调用的:hasattr[实例,字符串]
先看下这三个方法的作用:
hasattr:
 1 class Name():
 2     x = 'this is x'
 3 
 4     def f_a(self,attr):
 5         print(hasattr(self,attr))
 6 
 7 if __name__ == '__main__':
 8     n = Name()
 9     n.f_a('x')
10     n.f_a('y')
11     n.f_a('f_a')

运行结果:

1 C:\Users\lwj\AppData\Local\Programs\Python\Python37\python.exe D:/02Project/pacho/08day/反射/st_反射.py
2 True
3 False
4 True
5 
6 Process finished with exit code 0

从上面的例子可以看出,hasattr作用是判断实例是否有对应的属性(数据属性和方法属性),如果有返回True,没有则返回False

 

getattr:

 1 class Name():
 2     x = 'this is x'
 3 
 4     def f_a(self,attr):
 5         f = getattr(self,attr)
 6         print(type(f))
 7         print(f)
 8 
 9 if __name__ == '__main__':
10     n = Name()
11     n.f_a('x')
12     n.f_a('f_a')
13     n.f_a('y')

执行结果:

 1 C:\Users\lwj\AppData\Local\Programs\Python\Python37\python.exe D:/02Project/pacho/08day/反射/st_反射.py
 2 <class 'str'>
 3 this is x
 4 <class 'method'>
 5 <bound method Name.f_a of <__main__.Name object at 0x00000000020C28C8>>
 6 Traceback (most recent call last):
 7   File "D:/02Project/pacho/08day/反射/st_反射.py", line 49, in <module>
 8     n.f_a('y')
 9   File "D:/02Project/pacho/08day/反射/st_反射.py", line 41, in f_a
10     f = getattr(self,attr)
11 AttributeError: 'Name' object has no attribute 'y'
12 
13 Process finished with exit code 1

从上面的例子可以看出,getattr是根据传入的字符串来判断是否有对应属性,如果有对应属性,则返回该属性的值(内存地址);如果没有对应属性,则抛异常AttributeError

 

setattr:

 1 class Name():
 2     x = 'this is x'
 3     value = 10
 4 
 5     def f_a(self,attr):
 6         setattr(self,attr,self.value)
 7 
 8 
 9 if __name__ == '__main__':
10     n = Name()
11     print(n.x)
12     n.f_a('x')
13     print(n.x)

执行结果:

1 C:\Users\lwj\AppData\Local\Programs\Python\Python37\python.exe D:/02Project/pacho/08day/反射/st_反射.py
2 this is x
3 10
4 
5 Process finished with exit code 0

从上面的例子可以看出,setattr是吧实例的属性重新赋值,我们可以赋值为数据属性或者方法,上面是举例数据属性,下面举例设置方法:

 1 class Name():
 2     x = 'this is x'
 3     def value(self):
 4         print('I am value')
 5 
 6     def f_a(self,attr):
 7         setattr(self,attr,self.value)  # 这里只传方法名,而不是self.value()   这样会把方法的返回值赋值给属性
 8 
 9 
10 if __name__ == '__main__':
11     n = Name()
12     print(n.x)
13     n.f_a('x')
14     print(n.x)
15     n.x()

执行结果:

1 C:\Users\lwj\AppData\Local\Programs\Python\Python37\python.exe D:/02Project/pacho/08day/反射/st_反射.py
2 this is x
3 <bound method Name.value of <__main__.Name object at 0x0000000002584988>>
4 I am value
5 
6 Process finished with exit code 0

 

总结:

hasattr

使用:hasattr(obj,'属性')

作用:判断实例obj是否具有某属性,有则返回True,无则返回False

 

getattr

使用:getattr(obj,'属性')

作用:获取obj的属性(一般赋值给变量)

 

setattr

使用:setattr(obj,'属性',属性值)

作用:给obj的属性赋值(值可以是数据属性,也可以是具体的方法,或者方法的返回值)

 

标签:__,反射,attr,setattr,self,getattr,Name,hasattr,属性
来源: https://www.cnblogs.com/wjlv/p/11649667.html