Python delattr 用法详解及示例
Python中的delattr()函数用于删除对象的属性。
函数的语法如下:
delattr(object, attribute)
其中,object是要删除属性的对象,attribute是要删除的属性名。
下面是3个示例:
示例1:删除对象的属性
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
p = Person("Alice", 25)
print(p.name)   # 输出:Alice
delattr(p, "name")
print(p.name)   # 输出:AttributeError: 'Person' object has no attribute 'name'
在上面的示例中,我们定义了一个Person类,然后创建了一个p对象。之后,使用delattr()函数删除了p对象的name属性。最后,当我们尝试访问p.name时,会报错提示属性不存在。
示例2:删除模块中的属性
import math
print(math.pi)   # 输出:3.141592653589793
delattr(math, "pi")
print(math.pi)   # 输出:AttributeError: module 'math' has no attribute 'pi'
在上面的示例中,我们首先导入了math模块,然后尝试输出math.pi的值。接着,使用delattr()函数删除了math模块的pi属性。最后,当我们再次尝试输出math.pi时,会报错提示属性不存在。
示例3:删除自定义类的方法
class Car:
    def __init__(self, brand):
        self.brand = brand
    def drive(self):
        print("Driving the", self.brand)
c = Car("Tesla")
c.drive()   # 输出:Driving the Tesla
delattr(Car, "drive")
c.drive()   # 输出:AttributeError: 'Car' object has no attribute 'drive'
在上面的示例中,我们定义了一个Car类,其中包含一个名为drive()的方法。然后,创建了一个c对象并调用了drive()方法。接着,使用delattr()函数删除了Car类的drive方法。最后,当我们再次尝试调用c.drive()时,会报错提示属性不存在。
极客教程