python之attr属性、包装、授权

一、attr属性

1.1getattr属性

class Foo:
    x=1
    def __init__(self,y):
        self.y=y
    def __getattr__(self, item):
        print('执行__getattr__')

f1=Foo(10)
print(f1.y)
print(f1,'y')

f1.aaaa          #调用一个对象不存在的属性时,会自动触发getattr

1.2delattra属性

class Foo:
    x=1
    def __init__(self,y):
        self.y=y
    def __delattr__(self, item):
        print('删除操作__delattr__')

f1=Foo(10)
del f1.y
print(f1.x)
del f1.x     #删除属性时,会触发delattr

1.3setattr属性

class Foo:
    x=1
    def __init__(self,y):
        self.y=y

    def __setattr__(self,key,value):
        print('执行__setattr__')
        self.__dict__[key]=value

f1=Foo(10)
print(f1.__dict__)
f1.z=2                 #设置属性时,会自动触发__setattr__
print(f1.__dict__)

二、包装和授权

2.1包装的概念

包装:python为大家提供了标准数据类型,以及丰富的内置方法,其实在很多场景下我们都需要基于标准数据类型来定制我们自己的数据类型,新增/改写方法,这就用到了我们所学的继承/派生知识(其他的标准类型均可以通过下面的方式进行二次加工)

# 包装(二次加工标准类型)
# 继承 + 派生 的方式实现 定制功能
1、重新定义append方法
2、定制新的功能
class List(list):
    def append(self,object): #append类型必须是字符串
        if type(object) is str:
            print("正在添加[%s]"%object)
            #list.append(self,object)#调用父类方法
            super().append(object)
        else:
            print("必须是字符串类型")
    def show_midlle(self):   #取传入值得中间字符
        mid_index = int(len(self)/2)
        return self[mid_index]
f1 = List("helloworld")
f1.append("SB")
print(f1)
f1.append(2222222)
print(f1.show_midlle())
View Code

2.2授权的介绍
授权:授权是包装的一个特性, 包装一个类型通常是对已存在的类型的一些定制,这种做法可以新建,修改或删除原有产品的功能。其它的则保持原样。授权的过程,即是所有更新的功能都是由新类的某部分来处理,但已存在的功能就授权给对象的默认属性。

实现授权的关键点就是覆盖__getattr__方法

#组合的方式继承了open函数的所有特性
class FileHandle:
    def __init__(self,filename,mode = "w",encoding = "utf-8"):
        self.file = open(filename,mode,encoding=encoding)
        self.mode = mode
        self.encoding = encoding
    def __getattr__(self,item):
        return getattr(self.file,item)
f1 = FileHandle("a.txt")
f1.write("1111
")
View Code
组合的方式定制写的方法
import time
class FileHandle:
    def __init__(self,filename,mode = "a+",encoding = "utf-8"):
        self.file = open(filename,mode,encoding=encoding)
        self.mode = mode
        self.encoding = encoding
    def write(self,len):
        t = time.strftime("%Y-%m-%d %X")
        self.file.write("%s %s"%(t,len))
    def __getattr__(self,item):
        return getattr(self.file,item)
f1 = FileHandle("a.txt")
f1.write("cpu负载过高
")
f1.write("内存剩余不足
")
f1.write("硬盘剩余不足
")
View Code
原文地址:https://www.cnblogs.com/changzhendong/p/11317281.html