hasattr() 函数用于判断对象是否包含对应的属性。
hasattr 语法:
hasattr(object, name)
#!/usr/bin/python # -*- coding: UTF-8 -*- class Coordinate: x = 10 y = -5 z = 0 point1 = Coordinate() print(hasattr(point1, 'x')) print(hasattr(point1, 'y')) print(hasattr(point1, 'z')) print(hasattr(point1, 'no')) # 没有该属性 True True True False
getattr() 函数用于返回一个对象属性值。
getattr 语法:
getattr(object, name[, default])
>>>class A(object): ... bar = 1 ... >>> a = A() >>> getattr(a, 'bar') # 获取属性 bar 值 1 >>> getattr(a, 'bar2') # 属性 bar2 不存在,触发异常 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'A' object has no attribute 'bar2' >>> getattr(a, 'bar2', 3) # 属性 bar2 不存在,但设置了默认值 3 >>>