zoukankan      html  css  js  c++  java
  • 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']
  • 相关阅读:
    7.12Java+TestNG环境搭建
    7.15Java之调用API接口传表单获取返回信息
    7.12理解Cookie与token
    7.13一次完整的Http请求过程(3)
    7.13一次完整的Http请求过程(2)
    7.13一次完整的Http请求过程
    PostgreSql安装(win 2003 下)
    实用工具(渐变更新中)
    .net Ajax系列(2)调用多Web Service
    .net Ajax系列(1)调用Web Service
  • 原文地址:https://www.cnblogs.com/big-handsome-guy/p/8618078.html
Copyright © 2011-2022 走看看