from collections import OrderedDict
class FIFO(OrderedDict):
def __init__(self, capacity=3,*args,**kwargs):
self.capacity = capacity #写到super()下面,就报错无capacity属性
super(FIFO,self).__init__(*args,**kwargs) #OrderedDict.__init__(self,*args,**kwargs)
def __setitem__(self, key, value):
if key in self:
print(‘delete existed key:‘,(key,self[key]))
del self[key]
elif len(self)==self.capacity: #表面是批量添加key,实则逐一添加,用>=就画蛇添足了
front=self.popitem(last=False)
print(‘delete front key:‘,front)
# 如同上文的构造函数,要用到父类的同名函数时,须等到结尾,才来显式调用它
OrderedDict.__setitem__(self, key, value) #super(FIFO,self).__setitem__(key, value)
fd=FIFO(3,{‘w‘:7,‘x‘:8,‘y‘:9,‘z‘:0})
print(fd)
fd.update([(‘a‘,1),(‘b‘,2),(‘c‘,3),(‘d‘,4),(‘e‘,5)])
print(fd)
fd.update({‘f‘:6,‘e‘:9})
print(fd)
****************************************分割线****************************************
类继承中的super:
1、super多重继承的构造及实例函数,同普通多继承:广度优先,懒惰模式,即在匹配到第一个长辈类后就终止。
2、但是若首个长辈类也有super,就是贪婪模式了:公共爷类(如class E继承了B?C?D,而B?C?D又都继承了A),仅执行一次;各父类的super前的代码是广度顺序,之后的代码是广度逆序。
class A:
def __init__(self):
print("Enter A")
print("Leave A")
class B(A):
def __init__(self):
print("Enter B")
super(B, self).__init__()
print("Leave B")
class C(A):
def __init__(self):
print("Enter C")
super(C, self).__init__()
print("Leave C")
class D(A):
def __init__(self):
print("Enter D")
super(D, self).__init__() #此句取注或注释后,各运行一次,观察两次结果的区别
print("Leave D")
class E(B, C, D):
def __init__(self):
print("Enter E")
super(E, self).__init__()
print("Leave E")
E()