首頁  >  文章  >  後端開發  >  Python內建函數-hasattr&setattr&getattr&delattr

Python內建函數-hasattr&setattr&getattr&delattr

黄舟
黄舟原創
2017-01-19 16:41:161770瀏覽

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的內容,更多相關內容請關注PHPP.S.


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn