python类的授权方式

继承的方式

利用类的继承来改写原有list方法:
class List(list):
    def append(self,value):
        if not isinstance(value, str):
            raise TypeError("must be string")
        super().append(value + "sb")
    def insert(self,index,value):
        if not isinstance(value,str):
            raise TypeError("must be string")
        super().insert(index, value + "sb")
l1 = List()
l1.append("egon")
print(l1)
l1.insert(0, "yuan")
print(l1)
l1.pop(-1)
print(l1)
'''
output:
['egonsb']
['yuansb', 'egonsb']
['yuansb']

授权的方式

授权的方式主要在于__getattr__将没有定义的方法映射到真正的内建函数file里面
import time
class File:
    def __init__(self,filepath,md = 'r',encode = 'utf-8'):
        self.file = open(filepath, mode = md, encoding = encode)
    def write(self,string):
        time_str = time.strftime('%Y-%m-%d')
        self.file.write("%s %s" %(time_str,string))
        self.file.close()
    def __getattr__(self,act):
        return getattr(self.file,act)
f1 = File("a.txt", md='w', encode='utf-8')
f1.write("surprise! Motherfucker!")
f1 = File("a.txt", md='r', encode='utf-8')
for x in f1.file:
    print(x)
'''
output : 2017-04-24 surprise! Motherfucker!
'''

作业

基于授权定制自己的列表类型,要求定制的自己的__init__方法,
定制自己的append:只能向列表加入字符串类型的值
定制显示列表中间那个值的属性(提示:property)
其余方法都使用list默认的(提示:__getattr__加反射)
class List:
	def __init__(self,list1):
		self.list1 = []
		if list1:
			for x in list1:
				self.list1.append(str(x))
	def append(self,value):
		if not isinstance(value,str):
			raise TypeError("must be string!")
		self.list1.append(value)
	def __getattr__(self,list_act):
		return getattr(self.list1,list_act)
	@property
	def display_mid(self):
		list_mid = int(len(self.list1)/2)
		return str(self.list1[list_mid])
	def __str__(self):
		return str(self.list1)
a = [1111,2222,3333]
l1 = List(a)
print(l1)
l1.append("1")
print(l1)
l1.insert(0,'333333333')
print(l1)
print(l1.display_mid)
''' 
output:
['1111', '2222', '3333']
['1111', '2222', '3333', '1']
['333333333', '1111', '2222', '3333', '1']
'2222'
'''
原文地址:https://www.cnblogs.com/anyanyaaaa/p/6758508.html