网站首页 > 基础教程 正文
前言
上一篇我们讲到了当实例对象获取一个不存在的属性时,只要你重载了__getattr()__,就能定制错误提示。有了__getattr__(), 那必须有 __setattr__(),这篇我们就来聊下 __setattr__() 魔法方法。
__setattr__()
__setattr__(self,key,value) 当一个属性被设置时的行为 在类实例的每个属性进行赋值时,都会首先调用__setattr__()方法,并在__setattr__()方法中将属性名和属性值添加到类实例的__dict__属性中。
>>> class Animal():
... def __init__(self,name,age):
... print(self.__dict__)
... self.name = name
... print(self.__dict__)
... self.age = age
... print(self.__dict__)
...
>>> dog = Animal('kitty',20)
{}
{'name': 'kitty'}
{'name': 'kitty', 'age': 20}
上面的示例中, 我们虽然没有重载__setattr__()方法,但是我们能看的出在调用__init__()方法对属性赋值时__dict__中依次插key 和 value。下面的示例将重载__setattr__(),来动态的演示实例属性赋值时__dict__的变化。
>>> class Animal():
... def __init__(self,name,age):
... self.name = name
... self.age = age
... def __setattr__(self,key,value):
... print('-'*30)
... print('setting:{},with:{}'.format(key,vaule))
... print("current __dict__: {}".format(self.__dict__))
... self.__dict__[key] = value
...
>>> dog = Animal('kitty', 20)
------------------------------
setting:name,with:kitty
current __dict__: {}
------------------------------
setting:age,with:20
current __dict__: {'name': 'kitty'}
可以看出,__init__()中两个属性赋值时,每次都会调用一次__setattr__()方法,__dict__也是从无到有。__setattr__ 负责在__dict__中对属性进行注册,所以 self.__dict__[key] = value 必不可少,大家可以试下,如果没有这句话,会报什么错?
往期回顾
python魔法方法连载二 --getattr()python魔法方法连载一 -- str() 和 repr()
猜你喜欢
- 2024-10-31 如何用 GitHub Actions 写出高质量的 Python代码?
- 2024-10-31 Python集成ActiveMQ,异步发送处理消息,详细代码手把手操作
- 2024-10-31 CentOS 7下编译安装Python3 centos7安装python3.7
- 2024-10-31 3分钟掌握Python 中的集合 python中集合的概念
- 2024-10-31 Python3 集合 python 集合 discard
- 2024-10-31 群晖安装python3 群晖安装python3.7
- 2024-10-31 Python的设计还是很精妙的,三分钟理解__get__和__set__
- 2024-10-31 十六、Python集合set常用方法 python set集合和list集合的区别
- 2024-10-31 python数据类型-集合set python set集合取值
- 2024-10-31 python笔记18:set 集合 python set集合取值
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- 单例 (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)