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  深圳

 

相关文章:

  • 2022-12-23
  • 2021-08-11
  • 2021-10-06
  • 2021-09-19
  • 2022-12-23
  • 2022-12-23
  • 2022-01-04
  • 2022-01-10
猜你喜欢
  • 2022-12-23
  • 2021-08-30
  • 2022-02-01
  • 2021-12-24
  • 2022-12-23
  • 2021-12-29
  • 2022-02-18
相关资源
相似解决方案