Python內置函數(27)——hasattr


英文文檔:

hasattr (object, name)
The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)
說明:
  
  1. 函數功能用來檢測對象object中是否含有名為name的屬性,如果有則返回True,如果沒有返回False
#定義類A
>>> class Student:
    def __init__(self,name):
        self.name = name

        
>>> s = Student('Aim')
>>> hasattr(s,'name') #a含有name屬性
True
>>> hasattr(s,'age') #a不含有age屬性
False

  2. 函數實際上是調用getattr(object,name)函數,通過是否拋出AttributeError來判斷是否含有屬性。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM