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"))
运行结果: