Python3.6内置函数(14)——delattr()

浏览: 1685

英文文档

delattr(object, name)

This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, ‘foobar’) is equivalent to del x.foobar.

delattr()

1、函数作用用来删除指定对象的指定名称的属性,和setattr函数作用相反。

>>> #定义类A
>>> class A:
      def __init__(self, name):
            self.name = name
      def hello(self):
            print('hello', self.name)
>>> #测试属性和方法
>>> a = A('你好')
>>> a.name
'你好'
>>> a.hello()
hello 你好
>>> #删除属性
>>> delattr(a, 'name')
>>> a.name
Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    a.name
AttributeError: 'A' object has no attribute 'name'


2、当属性不存在的时候,会报错。

>>> a.name  #属性name已经删掉,不存在
Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    a.name
AttributeError: 'A' object has no attribute 'name'
>>> delattr(a,'name') #再删除会报错
Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    delattr(a,'name') #再删除会报错
AttributeError: name


3、不能删除对象的方法。

>>> a.hello
<bound method A.hello of <__main__.A object at 0x0000000002FD7668>>
>>> delattr(a, 'hello') #不能用于删除方法
Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    delattr(a, 'hello') #不能用于删除方法
AttributeError: hello

小结

希望通过上面的操作能帮助大家。如果你有什么好的意见,建议,或者有不同的看法,希望你留言和我进行交流、讨论。

欢迎关注微信公众号,访问更多精彩:数据之魅

如需转载,请联系授权,谢谢合作。

火狐截图_2019-06-29T07-07-45.688Z.png

推荐 0
本文由 Airy 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册