Python内置函数——hasattr&setattr&getattr&delattr

黄舟
发布: 2017-01-19 16:41:16
原创
1784 人浏览过

Python内置函数——hasattr&setattr&getattr&delattr

hasattr & setattr & getattr & delattrhasattr(object,name):用于判断一个对象里中是否存在name这一特性.
setattr(object, name, value):该函数给对象中的属性赋值,该属性若不存在,则会在对象里创建新的属性
delattr(object, name):删除指定对象的属性,可以配合hasattr使用
getattr(object, name[, default]),object为对象名,naem为对象属性(必须是字符串),
default为name属性不存在时指定的返回内容(可以是字符串,也可以是部分指令),
若对象中存在该属性,则函数返回object.name,
否则返回default中的内容,若省略default,则返回 AttributeError.
In [4]: class test(object):
   ...:     name = "john"
   ...:     def greet(self):
   ...:         print "hello,my name is %s"% name
   ...:
In [5]: a = test()
In [6]: hasattr(a,'name')
Out[6]: True
In [7]: hasattr(a,'greet')
Out[7]: True
In [8]: setattr(a,'name','mark')
In [9]: print a.name
mark
In [10]: getattr(a,'name','no exit')
Out[10]: 'mark'
In [11]: getattr(a,'greet','no exit')
Out[11]: <bound method test.greet of <__main__.test object at 0x0000000003AB8470
>>
In [12]: getattr(a,&#39;age&#39;,&#39;no exit&#39;)
Out[12]: &#39;no exit&#39;
In [13]: setattr(a,&#39;name&#39;,&#39;jane&#39;)
In [14]: a.name
Out[14]: &#39;jane&#39;
In [15]: setattr(a,&#39;age&#39;,20)
In [16]: a.age
Out[16]: 20
In [17]: getattr(a,&#39;nationality&#39;,setattr(a,&#39;nationality&#39;,&#39;Englend&#39;))
Out[17]: &#39;Englend&#39;
In [18]: a.nationality
Out[18]: &#39;Englend&#39;
In [19]: if hasattr(a,&#39;age&#39;):
   ....:     delattr(a,&#39;age&#39;)
   ....:
In [20]: a.age
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-20-d50340e1fbb7> in <module>()
----> 1 a.age
AttributeError: &#39;test&#39; object has no attribute &#39;age&#39;
In [21]: b = test()
In [22]: b.nationality
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-22-fd8c7f39aa50> in <module>()
----> 1 b.nationality
AttributeError: &#39;test&#39; object has no attribute &#39;nationality&#39;
登录后复制

以上就是Python内置函数——hasattr&setattr&getattr&delattr的内容,更多相关内容请关注PHP中文网(www.php.cn)!


来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板