hasattr(),作用是检查某个对象是否具有指定的属性。接收两个参数:对象和属性名。如果该对象具有指定的属性,则返回True,否则返回False。
setattr(), 作用是添加属性,可动态添加属性
例如:
class P(object):
def __init__(self, p_name, p_age):
self.name = p_name
self.age = p_age
p = P("XiaoMing", 20)
# 检查对象是否具有属性
has_name = hasattr(p, "name")
has_address = hasattr(p, "taikang")
print(f"name attr exist: {has_name}")
print(f"address attr exist: {has_address }")
name attr exist:True
address attr exist: False
----------------------------------------------------------------
# 动态添加一个属性
setattr(p, "sex", "boy")
# 现在我们可以访问新添加的属性
print(f"add attr sex: {p.sex}")
add attr sex:boy