请稍候,加载中....

类的特殊方法(四)

这一组方法用于自定义对象属性的方法

__getattribute__方法

obj.__getattribute__(name), 返回指定的name属性, 属性不存在, 抛出AttributeError

class A:

    def __init__(self, value):
        self.value = value

    def __getattribute__(self, name):
        print("调用该方法")
        return super().__getattribute__(name)

a1 = A(10)

print(a1.value)
print(getattr(a1, "value"))
print(a1.key) # 抛出异常AttributeError

__getattr__方法

在__getattribute__异常时调用

class A:

    def __init__(self, value):
        self.value = value

    def __getattribute__(self, name):
        print("调用该方法")
        return super().__getattribute__(name)

    def __getattr__(self, name):
        return f"{name}不存在"

a1 = A(10)

print(a1.key)

__setattr__方法

obj.__setattr__(name, value), 用于给属性name赋值value

class A:

     def __setattr__(self, name, value):
           print(name, value)
           return super().__setattr__(name, value)

a1 = A()
a1.a = 10
setattr(a1, "b", 100)

__delattr__方法

obj.__delattr(name), 当删除属性name时,触发该方法

class A:
    
    def __init__(self, a, b):
        self.a = a
        self.b = b
        
    def __delattr__(self, name):
        print(name)
        if name == "a":
            super().__delattr__(name)

a1 = A(10, 100)
del a1.a
del a1.b # 无法删除b

__dir__方法

当dir(obj)时, 调用该方法, 返回一个可迭代对象

class A:
    a = 10
    b = 100
    def __dir__(self):
        print("this is dir")
        return self.__dict__

a1 = A()
print(dir(a1))

 

 


Python学习手册-