python中的对象属性支持增删改查等操作
class Dog:
"""狗"""
def __init__(self,name):
self.name = name
self.age = 0
dog1 = Dog("大黄")
dog2 = Dog("财财")
1. 查
- 对象.属性 - 获取指定对象指定属性对应的值,如果属性不存在会报错
- getattr(对象,属性名,默认值) -获取指定对象指定属性对应的值;当属性不存在有默认值的时候不报错,返回默认值.没有默认值的时候报错
print(dog1.name) # 大黄
# print(dog1.name2) # AttributeError: 'Dog' object has no attribute 'name2'
print(getattr(dog1, 'name2', 100)) # 100
2.增,改
- 对象.属性 = 值 -当属性不存在就添加属性,当属性存在修改属性的值
- setattr(对象,属性名,值) -当属性不存在就添加属性,当属性存在修改属性的值
dog1.gender = '雌'
print(dog1.gender) # 雌
dog1.name = '贝贝'
print(dog1.name) # 贝贝
a_name = 'color'
setattr(dog1, 'color', '白色')
print(getattr(dog1, 'color')) # 白色
setattr(dog1, 'name', '金金')
print(dog1.name) # 金金
3.删
- del 对象.属性
- delattr(对象,属性名)
del dog1.name
# print(dog1.name) # AttributeError: 'Dog' object has no attribute 'name'
delattr(dog1, 'age')
# print(dog1.age) # AttributeError: 'Dog' object has no attribute 'age'
# 注意: 对象属性的增删改查只针对单个对象
# print(dog2.gender) # AttributeError: 'Dog' object has no attribute 'gender'
print(dog2.name, dog2.age) # 财财 0