hasattr() 函數用來判斷某個類實例對象是否包含指定名稱的屬性或方法。
hasattr() 函數源碼如下:
def hasattr(*args, **kwargs): # real signature unknown
"""
Return whether the object has an attribute with the given name.
This is done by calling getattr(obj, name) and catching AttributeError.
"""
pass
語法格式如下:
hasattr(obj, name)
示例代碼:
class Test(object):
def __init__(self):
self.name = "張三"
self.age = 25
def say(self):
print("I love study!")
obj = Test()
print(hasattr(obj, "name"))
print(hasattr(obj, "age"))
print(hasattr(obj, "say"))
print(hasattr(obj, "new_name"))
運行結果: