鱼C论坛

 找回密码
 立即注册
查看: 2133|回复: 0

[学习笔记] python魔法方法之属性访问

[复制链接]
发表于 2018-5-25 18:00:56 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
一、__getattr__(self,name):定义当用户试图获取一个不存在的属性时的行为

二、__getattribute__(self,name):定义当该类的属性被访问时的行为

三、__setattr__(self,name,value):定义当一个属性被设置时的行为

四、__delattr__(self,name):定义当一个属性被删除时的行为

class C:
    def __getattr__(self, name):#定义当用户试图获取一个不存在的属性时的行为
        print('getattr')
    def __setattr__(self, name, value):
        print('setattr')
        super().__setattr__(name,value)
    def __delattr__(self, name):
        print('delattr')
        super().__delattr__(name)
    def __getattribute__(self, name):#定义当该类的属性被访问时的行为,因此访问属性时最先被调用
        print('getattribute')
        return super().__getattribute__(name)

c = C()
c.x#结果时先打印了getattribute,然后又调用了getattr
c.x = 1#结果是打印setattr
c.x#结果时打印getattribute,不会再打印getattr,因为此时属性已经存在
del c.x#结果是打印delattr
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 16:42

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表