super
这是Guido内置的纯 Python 实现示例,用于说明目的。Super
我需要对以下类的实现进行一些说明
在下面的代码中调用someobj.__mro__
将不起作用。请参阅我对这条线的评论。内置super
简单地抛出错误。
TypeError: super(type, obj): obj must be an instance or subtype of type
问题:
我的问题是,当初设立这条线的目的是什么?
因此,如果传入的对象不是传入类的实例,则开始使用该对象的 mro...为什么?
class Super(object):
def __init__(self, type, obj=None):
self.__type__ = type
self.__obj__ = obj
def __get__(self, obj, type=None):
if self.__obj__ is None and obj is not None:
return Super(self.__type__, obj)
else:
return self
def __getattr__(self, attr):
if isinstance(self.__obj__, self.__type__):
starttype = self.__obj__.__class__
else:
starttype = self.__obj__ ## This line does not work
mro = iter(starttype.__mro__)
for cls in mro:
if cls is self.__type__:
break
# Note: mro is an iterator, so the second loop
# picks up where the first one left off!
for cls in mro:
if attr in cls.__dict__:
x = cls.__dict__[attr]
if hasattr(x, "__get__"):
x = x.__get__(self.__obj__)
return x
raise AttributeError, attr
class A(object):
def m(self):
''' m in A'''
return "A"
class B(A):
def m(self):
''' m in B'''
return "B" + Super(B, self).m()
class C(A):
def m(self):
''' m in C '''
return "C" + Super(C, self).m()
class D(C):
def m(self):
''' m in D'''
return "D" + Super(B, self).m()
print D().m() # "DCBA"
堆栈跟踪:
Traceback (most recent call last):
File "./supertest.py", line 73, in <module>
print D().m() # "DCBA"
File "./supertest.py", line 71, in m
return "D" + Super(B, self).m()
File "./supertest.py", line 33, in __getattr__
mro = iter(starttype.__mro__)
AttributeError: 'D' object has no attribute '__mro__'