Python __getattr__与__setattr__使用方法
时间:2021-10-17 09:17:53
比如下面的例子:
class Book(object):
def __setattr__(self, name, value):
if name == 'value':
object.__setattr__(self, name, value - 100)
else:
object.__setattr__(self, name, value)
def __getattr__(self, name):
try:
return object.__getattribute__(name)
except:
return name + ' is not found!'
def __str__(self):
return self.name + ' cost : ' + str(self.value)
c = Book()
c.name = 'Python'
c.value = 100
print c.name
print c.value
print c
print c.Type
上面的例子中,在赋值书的value属性时,偷偷的将value减去了100,呵。输出结果:
Python
0
Python cost : 0
Type is not found!
标签:Python,getattr,setattr
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python实现针对json中某个关键字段进行排序操作示例
2023-03-28 16:02:37
![](https://img.aspxhome.com/file/2023/4/127814_0s.png)
xhtml有哪些块级元素
2009-12-06 11:58:00
利用webstrom调试Vue.js单页面程序的方法教程
2023-06-27 01:21:25
![](https://img.aspxhome.com/file/2023/5/55905_0s.jpg)
浅谈Python从全局与局部变量到装饰器的相关知识
2022-06-02 12:23:26
Python实现批量修改xml文件的脚本
2022-01-14 06:14:03
![](https://img.aspxhome.com/file/2023/4/97494_0s.png)
python批量添加zabbix Screens的两个脚本分享
2022-07-21 02:17:28
如何用MySQL-Front远程连接MySql?
2010-12-03 16:02:00
python使用pandas实现数据分割实例代码
2021-07-02 11:09:19
Pycharm不同版本镜像源添加方法
2023-08-24 15:59:43
![](https://img.aspxhome.com/file/2023/2/77562_0s.jpg)
Python调用scp向服务器上传文件示例
2023-12-09 18:56:34
MySQL应用技巧之内存使用线程独享
2010-08-08 08:33:00
python实现二分查找算法
2022-08-30 21:58:54
根据选择的checkbox列出选择的值
2008-07-30 12:56:00
![](https://img.aspxhome.com/file/UploadPic/20087/30/200873013437517s.jpg)
ASP实现上传图片到数据库
2007-09-21 12:59:00
开发保留标准的浏览器功能的AJAX应用
2008-02-03 14:03:00
用Dreamweaver设计自动关闭的网页
2010-09-02 12:29:00
![](https://img.aspxhome.com/file/UploadPic/20072/200723113111210s.jpg)
Python使用文件锁实现进程间同步功能【基于fcntl模块】
2022-07-04 17:45:15
python替换字符串中的子串图文步骤
2021-06-23 22:02:47
![](https://img.aspxhome.com/file/2023/6/69006_0s.jpg)
Python生成器传参数及返回值原理解析
2022-03-17 08:58:40
PyCharm永久激活方式(推荐)
2023-06-12 00:53:33
![](https://img.aspxhome.com/file/2023/7/59467_0s.png)