Python基础之十二(动态设置类属性)
一、setattr() # 设置/修改属性
语法:setattr(对象名, 属性名, 属性值)
规则:属性不存在则添加属性,属性存在则修改属性值
例子:
class Student: type = '学生' def __init__(self): self.name = '小明' if __name__ == '__main__': stu = Student() print(Student.__dict__) # 当前类属性 setattr(Student, 'classroom', '五年级') # 添加类属性classroom print(Student.__dict__) setattr(Student, 'classroom', '六年级') # 修改类属性classroom print(Student.__dict__) print('==='*10) print(stu.__dict__) # 当前实例属性 setattr(stu, 'age', 12) # 添加实例属性 print(stu.__dict__) setattr(stu, 'name', '张三') # 修改实例属性 print(stu.__dict__)
输出结果:
<attribute '__weakref__' of 'Student' objects>, '__doc__': None} {'__module__': '__main__', 'type': '学生', '__init__': <function Student.__init__ at 0x0000000001E79160>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None, 'classroom': '五年级'} {'__module__': '__main__', 'type': '学生', '__init__': <function Student.__init__ at 0x0000000001E79160>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None, 'classroom': '六年级'} ============================== {'name': '小明'} {'name': '小明', 'age': 12} {'name': '张三', 'age': 12}
二、getattr() # 获取属性值
语法:getattr(对象名, 属性名, [默认值])
规则:属性存在则获取属性的值,不存在则返回默认值,注意:如果属性不存在,又没有设置默认值,则会报错
例子:
class Student: type = '学生' def __init__(self): self.name = '小明' if __name__ == '__main__': stu = Student() print(getattr(Student, 'type')) # 获取类的type属性值 print(getattr(stu, 'name')) # 获取实例的name属性值 print(getattr(stu, 'weight', 50)) # 获取实例的weight属性值,如果没有该属性则返回50
输出结果:
学生
小明
50
如果属性不存在,且没有设置默认值:
class Student: type = '学生' def __init__(self): self.name = '小明' if __name__ == '__main__': stu = Student() print(getattr(stu, 'weight')) # 获取实例的weight属性值
输出结果:(报错)
AttributeError: 'Student' object has no attribute 'weight'
三、delattr() # 删除属性
语法:delattr(对象名, 属性名)
规则:属性存在删除属性,不存在则会报错
例子:
class Student: type = '学生' def __init__(self): self.name = '小明' self.age = 12 if __name__ == '__main__': stu = Student() print(stu.__dict__) # 打印删除前实例属性 delattr(stu, 'age') # 删除实例属性age print(stu.__dict__) # 删除后实例属性
输出结果:
{'name': '小明', 'age': 12}
{'name': '小明'}
如果删除不存在的属性:
class Student: type = '学生' def __init__(self): self.name = '小明' self.age = 12 if __name__ == '__main__': stu = Student() delattr(Student, 'name') print(Student.__dict__)
输出结果:(报错)
AttributeError: name
四、hasattr() # 判断是否存在属性
语法:hasattr(对象名, 属性名)
规则:存在返回True,不存在返回False
例子:
class Student: type = '学生' def __init__(self): self.name = '小明' self.age = 12 if __name__ == '__main__': stu = Student() print(hasattr(Student, 'type')) # 判断Student类对象是否有type属性,真 print(hasattr(Student, 'name')) # 判断Student类对象是否有name属性,假(类不能访问实例属性) print(hasattr(stu, 'name')) # 判断stu实例对象是否有name属性,真 print(hasattr(stu, 'type')) # 判断stu实例对象是否有type属性,真(实例可以访问类属性) print(hasattr(stu, 'weight')) # 判断Student类是否有type属性,假
输出结果:
True
False
True
True
False

浙公网安备 33010602011771号