双下划线开头的attr方法

_ getattr_()
当调用一个不存在的属性时,就会触发__getattr__()

class Foo:
    x = 1

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

    def __getattr__(self, item):
        print("执行__getattr__()")
        print("不存在",item)


f1 = Foo(10)
print(f1.x)#调用存在的属性不会触发__getattr__()
f1.dsa#因为dsa属性不存在,所以会触发__getattr__(),将f1传给self,dsa传给item

_ delattr_()
删除一个属性的时候会触发__delattr__()

class Foo:
    x = 1

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

    def __getattr__(self, item):
        print("执行__getattr__()")
        print("不存在", item)

    def __delattr__(self, item):
        print("执行__delattr__()")
        #del self.item 这样写会进入死递归
        self.__dict__.pop(item)#这是删除操作的本质


f1 = Foo(10)
del f1.y

_ setattr_()
在改动属性或新增属性的时候会触发__setattr__()

class Foo:
    x = 1

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

    def __getattr__(self, item):
        print("执行__getattr__()")
        print("不存在", item)

    def __delattr__(self, item):
        print("执行__delattr__()")
        self.__dict__.pop(item)

    def __setattr__(self, key, value):
        print("执行__setattr__()")
        self.key = value#这样写会进入死递归
        self.__dict__[key] = value


f1 = Foo(10)

这些双下划綫开头的方法都是类内置的方法,可以通过dir(object)函数来查看
所有类内函数,都是如果有定义先调用定义的,没有定义则调用默认的

相对而言__getattr__()函数更有用,其他两个函数用的比较少

双下划綫开头的方法,只有在类的实例调用的时候才会触发


作用实例
1.当属性不存在时,不报错

class Foo:
    x = 1

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

    def __getattr__(self, item):
        print("执行__getattr__()")
        print("不存在", item)

    
f1 = Foo(10)
f1.age

2.所有属性都要求是字符串

class Foo:
    x = 1

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

    def __setattr__(self, key, value):
        if type(value) is str:
            self.__dict__[key] = value
            print("设置成功")
        else:
            print("属性内容必须是字符串,设置失败")


f1 = Foo(10)
f2 = Foo("CJJ")

3.所有属性都不允许删除

class Foo:
    x = 1

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

    def __delattr__(self, item):
        print("所有属性不允许删除")


f1 = Foo(10)
f1.name = "CJJ"
del f1.name
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值