英文文檔:
-
hasattr(object, name) -
The arguments are an object and a string. The result is
Trueif the string is the name of one of the object’s attributes,Falseif not. (This is implemented by callinggetattr(object, name)and seeing whether it raises anAttributeErroror 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來判斷是否含有屬性。
