Python built-in functions - hasattr&setattr&getattr&delattr

黄舟
Release: 2017-01-19 16:41:16
Original
1762 people have browsed it

Python built-in function——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;
Copy after login

The above is the content of Python built-in function——hasattr&setattr&getattr&delattr. For more related content, please pay attention to the PHP Chinese website (www.php. cn)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!