python 对象属性与 getattr & setattr
Python对象的属性可以通过obj.__dict__获得,向其中添加删除元素就可以实现python对象属性的动态添加删除的效果,不过我们应该使用更加正规的getattr和setattr来进行这类操作
- getattr(object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
getattr可以动态的获取对象的属性,default可以指定如果名为name的属性不存在时返回的值,如果不指定而object中又没有该属性名称,则返回AttributeError
- >>> class Demo(object):
- ... def __init__(self):
- ... self.name = 'Demo'
- ... def count(self):
- ... return len(self.name)
- ...
- >>> X = Demo()
- >>> X.count()
- 4
- >>> getattr(X, 'count')()
- 4
- >>> getattr(X, 'name')
- 'Demo'
- >>> getattr(X, 'notexist')
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- AttributeError: 'Demo' object has no attribute 'notexist'
- >>> getattr(X, 'notexist', 'default_value')
- 'default_value'
- setattr(object, name, value)
This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.
与getattr对应,setattr用来动态的设定一个对象的属性,用来构造配置类对象内非常合适
- >>> Y = Demo()
- >>> setattr(Y, 'color', 'red')
- >>> Y.color
- 'red'
当执行以上函数是类内有默认的方法进行响应,返回或者设置obj.__dict__中的属性,我们可以定义自己的这类函数,即为__getattr__, __setattr__,前者在obj.__dict__中找不到时会被调用
- object.__getattr__(self, name)
-
Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __getattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control in new-style classes.
- object.__setattr__(self, name, value)
-
Called when an attribute assignment is attempted. This is called instead of the normal mechanism (i.e. store the value in the instance dictionary). name is the attribute name, value is the value to be assigned to it.
If __setattr__() wants to assign to an instance attribute, it should not simply execute self.name = value — this would cause a recursive call to itself. Instead, it should insert the value in the dictionary of instance attributes, e.g., self.__dict__[name] = value. For new-style classes, rather than accessing the instance dictionary, it should call the base class method with the same name, for example, object.__setattr__(self, name, value).
- object.__delattr__(self, name)
-
Like __setattr__() but for attribute deletion instead of assignment. This should only be implemented if del obj.name is meaningful for the object.
通过在类中实现这些方法可以返回一些'计算'(得到的)属性
- >>> class Z:
- ... access_cnt = {}
- ... def __getattr__(self, name):
- ... cnt = self.access_cnt.get(name, 0)
- ... print 'access cnt:', cnt + 1
- ... self.access_cnt[name] = cnt + 1
- ...
- >>> z = Z()
- >>> z.hello
- access cnt: 1
- >>> z.hello
- access cnt: 2
- >>> z.hello
- access cnt: 3
- >>> z.world
- access cnt: 1
- >>> z.world
- access cnt: 2
python 对象属性与 getattr & setattr的更多相关文章
- 详解Python对象属性
在面向对象编程中,公开的数据成员可以在外部随意访问和修改,很难控制用户修改时新数据的合法性.解决这一问题的常用方法是定义私有数据成员,然后设计公开的成员方法来提供对私有数据成员的读取和修改操作,修改私 ...
- python对象属性管理(2):property管理属性
使用Property管理属性 python提供了一种友好的getter.setter.deleter类方法的属性管理工具:property. property()是一个内置函数,它返回一个Proper ...
- python动态函数hasattr,getattr,setattr,delattr
hasattr(object,name) hasattr用来判断对象中是否有name属性或者name方法,如果有,染回true,否则返回false class attr(): def fun( ...
- Python面试题之Python对象反射、类反射、模块反射
python面向对象中的反射:通过字符串的形式操作对象相关的属性.python中的一切事物都是对象(都可以使用反射) 一.getattr 对象获取 class Manager: role = &quo ...
- python遍历并获取对象属性--dir(),__dict__,getattr,setattr
一.遍历对象的属性: 1.dir(obj) :返回对象的所以属性名称字符串列表(包括属性和方法). for attr in dir(obj): print(attr) 2.obj.__dict__:返 ...
- python全栈开发day23-面向对象高级:反射(getattr、hasattr、setattr、delattr)、__call__、__len__、__str__、__repr__、__hash__、__eq__、isinstance、issubclass
一.今日内容总结 1.反射 使用字符串数据类型的变量名来操作一个变量的值. #使用反射获取某个命名空间中的值, #需要 #有一个变量指向这个命名空间 #字符串数据类型的名字 #再使用getattr获取 ...
- python 零散记录(七)(下) 新式类 旧式类 多继承 mro 类属性 对象属性
python新式类 旧式类: python2.2之前的类称为旧式类,之后的为新式类.在各自版本中默认声明的类就是各自的新式类或旧式类,但在2.2中声明新式类要手动标明: 这是旧式类为了声明为新式类的方 ...
- python中hasattr()、getattr()、setattr()函数的使用
1. hasattr(object, name) 判断object对象中是否存在name属性,当然对于python的对象而言,属性包含变量和方法:有则返回True,没有则返回False:需要注意的是n ...
- Python面向对象基础:设置对象属性
用类存储数据 类实际上就是一个数据结构,对于python而言,它是一个类似于字典的结构.当根据类创建了对象之后,这个对象就有了一个数据结构,包含一些赋值了的属性.在这一点上,它和其它语言的struct ...
随机推荐
- 用python实现按权重对N个数据进行选择
需求:某公司有N个人,根据每个人的贡献不同,按贡献值给每个人赋予一个权重.设计一种算法实现公平的抽奖. 需求分析:按照权重对数据进行选择. 代码实现: 1 def fun(n,p): 2 " ...
- js闭包引起的事件注册问题
背景:闲暇时间看了几篇关于js作用域链与闭包的文章,偶然又看到了之前遇到的一个问题,就是在for循环中为dom节点注册事件驱动,具体见下面代码: <!DOCTYPE html> <h ...
- [Swift实际操作]九、完整实例-(4)在项目中使用CocoaPod管理类库和插件
本文将为你演示,如何使用CocoaPod第三方类库管理工具,在项目中安装未来需要使用的类库.首先创建一份文本文件.可以使用一个脚本创建文件,你可以采用自己的方式是创建一份文本文件,接着在文件名称上点击 ...
- Effective Java 3rd.Edition 翻译
推荐序 前言 致谢 第一章 引言 第二章 创建和销毁对象 第1项:用静态工厂方法代替构造器 第2项:遇到多个构造器参数时要考虑使用构建器 第3项:用私有构造器或者枚举类型强化Singleton属性 第 ...
- 11、C内存四区模型
转载于:https://blog.csdn.net/wu5215080/article/details/38899259 内存四区模型 图1.内存四区模型流程说明1.操作系统把物理硬盘代码load到内 ...
- Android 对话框的应用1
1.介绍 2.作用 (1)消息提示对话框 (2)简单列表对话框 (3)单选列表对话框 (4)多选对话框 (5)自定义对话框 3.java后台代码 package com.lucky.test28dia ...
- 正则表达式中模式修正符作用详解(i、g、m、s、x、e)
下面的转:http://www.cnblogs.com/shunyao8210/archive/2008/11/13/1332591.html 总结1:附件参数g的用法 表达式加上参数g之后,表明可以 ...
- 基于PHPExcel的常用方法总结
// 通常PHPExcel对象有两种实例化的方式// 1. 通过new关键字创建空白文档$phpexcel = newPHPExcel();// 2. 通过读取已有的模板创建$phpexcel =PH ...
- Angular 怎么在加载中加入 Loading 提示框
[转自] http://zhidao.baidu.com/link?url=MX9eSRkQbBC8zrjsCi-t_PsftVRSIjiaUTHhdp6eDiZ0IqaZehSCo3n7fFXWyP ...
- Oracle子分区(sub partition)操作
要重新定义大量分区表. 首先看 SQL Reference 大致了解了 Oracle 的分区修改操作.Alter table 语句的alter_table_partitioning 子句可以分为以下几 ...