#包装:继承基类,基于已存在的类型进行定制,进行二次加工
class List(list):
def append(self, object):
if type(object) is str:
super().append(object)
else:
print("必须是字符串类型")
l1 = List("hello")
l1.append("ss")
l1.append(11)
print(l1)
#授权:包装的一个特性,包装的类型通常是对以存在的类型进行定制,新建,修改,删除原功能
# 而授权是所有更新的功能由新类处理,已存在的功能授权给对象作为默认属性,不通过继承实现,用的组合
# 将系统内置的属性方法组合到自己定制的类中,作为默认属性,当自身的类未定制某个方法时,使用这些默认的属性
# 授权通过__getattr__方法
import time
class Open:
def __init__(self,filename,mode="r",encoding="utf-8"):
# self.filename = filename
self.file = open(filename,mode,encoding=encoding) #使用组合,调用系统的文件打开方法
self.mode = mode
self.encoding = encoding
def write(self,line): #自己定义,按照查找顺序,则优先使用自己的属性方法
t = time.strftime("%Y-%m-%d %X")
self.file.write("%s %s" %(t,line)) #使用系统内置的文件方法
def __getattr__(self, item):
print(item)
return getattr(self.file,item)
f1 = Open("a.txt","w")
print(f1.file)
print(f1.read) #触发__getattr__,在对象自身未找到方法,再到类中找,未找到,则触发getattr,调用内置open函数
f1.write("111")