类的内置方法__attr__介绍

1、hasattr  getaddr  setaddr delattr 这四个函数同样也适用于类

class BlackMedium:
    feture="Ugly"
    def __init__(self,name,addr):
        self.name=name
        self.addr=addr
    def sell_house(self):
        print("%s 正在卖房子,傻逼才买呢" %self.name)
    def rent_house(self):
        print("%s 正在租房子,傻逼才租呢" % self.name)
print(hasattr(BlackMedium,"feture"))

C:\python35\python3.exe D:/pyproject/day26/反射.py

True

2、双下划线开头的attr方法(__开头的都是内置的方法)

__getattr__

class Foo:
    x=1
    def __init__(self,y):
        self.y=y
    def __getattr__(self, item):
        print("执行__getattr__")
f1=Foo(10)
print(f1.y)
f1.ssss#当实例调用的方法不存在时候才会执行__getattr

C:\python35\python3.exe D:/pyproject/day26/双下划线开头的attr方法.py

10

执行__getattr__

__delattr__

class Foo:
    x=1
    def __init__(self,y):
        self.y=y
    def __delattr__(self, item):
        print("删除操作---->")
f1=Foo(10)
del f1.y#删除实例中的y 会触发__delattr__
del f1.x #删除类中的x 会触发__delattr__

C:\python35\python3.exe D:/pyproject/day26/双下划线开头的attr方法.py

删除操作---->

删除操作---->

__setattr__只要设置一次值,就会触发一次它

class Foo:
    x=1
    def __init__(self,y):
        self.y=y
    def __setattr__(self, key, value):
        print("__setattr__执行")
        self.__dict__[key]=value
f1=Foo(10)
print(f1.__dict__)
f1.z=2
print(f1.__dict__)

C:\python35\python3.exe D:/pyproject/day26/双下划线开头的attr方法.py

__setattr__执行

{'y': 10}

__setattr__执行

{'y': 10, 'z': 2}

3、如果调用的属性不存在,我们自己又没有定义__getattr的话,就会调用系统默认的

class Foo:
    pass
f1=Foo()
print(f1.xxx)#只有在属性不存在的时候,会自动触发__getattr__

AttributeError: 'Foo' object has no attribute 'xxx'

我们自己定义一个__getattr__,就会用我们自己的定义的这个

class Foo:
    def __getattr__(self, item):
        print("---->")
f1=Foo()
print(f1.xxx)#只有在属性不存在的时候,会自动触发__getattr__

C:\python35\python3.exe D:/pyproject/day26/双下划线开头的attr方法.py

---->

None

注意:

这__getattr__    __setattr__   __delattr__这三个只有实例化之后,实例调用的时候才会触发,跟类没有关系 

猜你喜欢

转载自www.cnblogs.com/gouguoqilinux/p/9208573.html