I have a question about python super().
here is my code
class A(object):
def test(self):
t = [self.__class__.__name__]
return t
class B(A):
def test(self):
t = super(B, self).test()
t.append(self.__class__.__name__)
return t
B().test()
the result is [B, B]
but i want to get [A, B]
is possible to get [A, B] ?
thanks all!
You can use __mro__ attribute of the class.
>>> class A(object):
... def test(self):
... return [c.__name__ for c in type(self).__mro__[-2::-1]]
...
>>> class B(A):
... pass
...
>>> B().test()
['A', 'B']
>>> A().test()
['A']
>>> B.__mro__
(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)
>>> B.__mro__[::-1]
(<type 'object'>, <class '__main__.A'>, <class '__main__.B'>)
>>> B.__mro__[-2::-1]
(<class '__main__.A'>, <class '__main__.B'>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With