• python 魔法方法补充(__setattr__,__getattr__,__getattribute__)


    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] = value
    
    a = 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] = value
    
    
    class 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'] = 1
    del f['a']
  • 相关阅读:
    mysql初识(五) 统计与计算与时间
    mysql初识(四)添加/修改字段信息
    mysql初识(二) 基础的查询语句
    mysql初识(三)修改表结构
    mysql初识(一)基础属性篇
    在Ubuntu上安装Docker Engine
    使用PowerDesigner对NAME和COMMENT互相转换
    mysql 5.1.34
    debian7下安装eclipse
    让 Visio 2003/2007 同时开多个独立窗口
  • 原文地址:https://www.cnblogs.com/big-handsome-guy/p/8618078.html
Copyright © 2020-2023  润新知