zoukankan      html  css  js  c++  java
  • Python内置函数(14)——delattr

    英文文档:

    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.
    说明:
      
      1. 函数作用用来删除指定对象的指定名称的属性,和setattr函数作用相反。
    #定义类A
    >>> class A:
        def __init__(self,name):
            self.name = name
        def sayHello(self):
            print('hello',self.name)
    
    #测试属性和方法
    >>> a.name
    '小麦'
    >>> a.sayHello()
    hello 小麦
    
    #删除属性
    >>> delattr(a,'name')
    >>> a.name
    Traceback (most recent call last):
      File "<pyshell#47>", line 1, in <module>
        a.name
    AttributeError: 'A' object has no attribute 'name'

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

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

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

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

    作者:〖十月狐狸〗

    出处:http://www.cnblogs.com/sesshoumaru/

    欢迎任何形式的转载,但请务必注明出处。

    本人水平有限,如果文章和代码有表述不当之处,还请不吝赐教。

  • 相关阅读:
    Redux API之compose
    Redux API之bindActionCreators
    Django组件-admin
    Django组件-分页器
    Django视图之FBV与CBV
    前端综合练习
    05-前端之jQuery
    关于DOM操作的案例
    04-再探JavaScript
    03-初识JavaScript
  • 原文地址:https://www.cnblogs.com/sesshoumaru/p/5989234.html
Copyright © 2011-2022 走看看