1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class People: def __init__(self,name,age): self.name = name self.age = age
def talk(self): print('%s is talking '%self.name)
obj = People('hjx',18)
# 判断是否含有属性和方法 print(hasattr(obj,'name')) print(hasattr(obj,'talk'))
# 拿到对象的属性或方法 # print(getattr(obj,'namexxxx')) 报错因为 没有该属性 # 兜底写法 print(getattr(obj,'namexxxx',None))
# 修改对象的属性 setattr(obj,'sex','man') print(obj.sex)
# 删除对象的属性 delattr(obj,'age') print(obj.__dict__)
# 类的属性也是可以获取的 print(getattr(People,'city'))
|