hasattr() 函数用来判断某个类实例对象是否包含指定名称的属性或方法。
- 无论是属性名还是方法名,都在 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)
- obj 指的是某个类的实例对象
- name 表示指定的属性名或方法名
- return True 或者 False
示例代码:
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"))
运行结果:

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/230242.html原文链接:https://javaforall.net
