Python标准库:内置函数hasattr(object, name)

Python标准库:内置函数hasattr(object, name)

本函数是用来判断对象object的属性(name表示)是否存在。如果属性(name表示)存在,则返回True,否则返回False。参数object是一个对象,参数name是一个属性的字符串表示。

例子:

 

[python] view plain copy
 
  1. #hasattr()  
  2.   
  3. class Foo:  
  4.     def __init__(self):  
  5.         self.x = 123  
  6.     def test(x):  
  7.         self.x = x  
  8.   
  9. foo = Foo()  
  10. print(hasattr(foo, 'x'))  
  11. print(hasattr(foo, 'y'))  
  12. print(hasattr(foo, 'test'))  

 

 

输出结果如下:

True

False

True

 

 

蔡军生 QQ:9073204  深圳

 

posted @ 2016-06-14 10:32  菜鸡一枚  阅读(216)  评论(0编辑  收藏  举报