class my_super:
def __init__(self, thisclass=None, target=None):
self._thisclass = thisclass
self._target = target
def _get_mro(self):
if issubclass(type, type(self._target)):
return self._target.__mro__ #第二个参数是类型
else:
return self._target.__class__.__mro__ #第二个参数是实例
def _get_function(self, name):
mro = self._get_mro()
if not self._thisclass in mro:
return None
index = mro.index(self._thisclass) + 1
while index < len(mro):
cls = mro[index]
if hasattr(cls, name):
attr = cls.__dict__[name]
#不要用getattr,因为我们这里需要获取未绑定的函数
#如果使用getattr, 并且获取的是classmethod
#会直接将cls绑定到该函数上
#attr = getattr(cls, name)
if callable(attr) or isinstance(attr, classmethod):
return attr
index += 1
return None
def __getattr__(self, name):
func = self._get_function(name)
if not func is None:
if issubclass(type, type(self._target)):
return func.__get__(None, self._target)
else:
return func.__get__(self._target, None)