博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 魔法方法补充(__setattr__,__getattr__,__getattribute__)
阅读量:4679 次
发布时间:2019-06-09

本文共 1698 字,大约阅读时间需要 5 分钟。

python 魔法方法补充

1 getattribute (print(ob.name) -- obj.func())当访问对象的属性或者是方法的时候触发

class F(object):            def __init__(self):            self.name = 'A'            def hello(self):            print('hello')            def __getattribute__(self, item):            print('获取属性,方法',item)            return object.__getattribute__(self,item)        a = F()    print(a.name)    a.hello()            获取属性,方法 name    A    获取属性,方法 hello    hello

2 getattr 拦截运算(obj.xx),对没有定义的属性名和实例,会用属性名作为字符串调用这个方法

class F(object):        def __init__(self):            self.name = 'A'            def __getattr__(self, item):            if item == 'age':                return 40            else:                raise AttributeError('没有这个属性')        f = F()    print(f.age)        # 40

3 setattr 拦截 属性的的赋值语句 (obj.xx = xx)

class F(object):    def __setattr__(self, key, value):        self.__dict__[key] = valuea = F()a.name = 'alex'print(a.name)

如何自定义私有属性:

class F(object):  # 基类--定义私有属性    def __setattr__(self, key, value):        if key in self.privs:            raise AttributeError('该属性不能改变')        else:            self.__dict__[key] = valueclass F1(F):    privs = ['age','name']  # 私有属性列表    # x = F1()    # x.name = 'egon'  # AttributeError: 该属性不能改变    # x.sex = 'male'class F2(F):    privs = ['sex']      # 私有属性列表    def __init__(self):        self.__dict__['name'] = 'alex'        # y = F2()        # y.name = 'eva'

getitem , setitem, delitem

class F(object):    def __getitem__(self,item):        print(item)    def __setitem__(self,key,value):        print(key,value)    def __delitem__(self,key):        print(key)f  = F()f['b']f['c'] = 1del f['a']

转载于:https://www.cnblogs.com/big-handsome-guy/p/8618078.html

你可能感兴趣的文章
LeetCode - Best Time to Buy and Sell Stock
查看>>
java-Coculator
查看>>
499 单词计数 (Map Reduce版本)
查看>>
python笔记
查看>>
昨天用的流量有点多60M
查看>>
kafka中的消费组
查看>>
Golang的channel使用以及并发同步技巧
查看>>
【JDK源码分析】 String.join()方法解析
查看>>
【SICP练习】112 练习3.28
查看>>
python--注释
查看>>
前端资源链接 ...
查看>>
yum install ntp 报错:Error: Package: ntp-4.2.6p5-25.el7.centos.2.x86_64 (base)
查看>>
leetcode-Single Number-136
查看>>
CF715C Digit Tree
查看>>
二分法练习1
查看>>
QT 制作串口调试小助手----(小白篇)
查看>>
前端MVC实践之hellorocket——by张舒彤
查看>>
OptimalSolution(2)--二叉树问题(3)Path路径问题
查看>>
IPC 之 Messenger 的使用
查看>>
爱情八十六课,等得不是爱情
查看>>