当前位置:Gxlcms > Python > Python内置函数——hasattr&setattr&getattr&delattr

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

时间:2021-07-01 10:21:17 帮助过:42人阅读

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,'age','no exit')
Out[12]: 'no exit'
In [13]: setattr(a,'name','jane')
In [14]: a.name
Out[14]: 'jane'
In [15]: setattr(a,'age',20)
In [16]: a.age
Out[16]: 20
In [17]: getattr(a,'nationality',setattr(a,'nationality','Englend'))
Out[17]: 'Englend'
In [18]: a.nationality
Out[18]: 'Englend'
In [19]: if hasattr(a,'age'):
   ....:     delattr(a,'age')
   ....:
In [20]: a.age
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-20-d50340e1fbb7> in <module>()
----> 1 a.age
AttributeError: 'test' object has no attribute 'age'
In [21]: b = test()
In [22]: b.nationality
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-22-fd8c7f39aa50> in <module>()
----> 1 b.nationality
AttributeError: 'test' object has no attribute 'nationality'

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

人气教程排行