Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python super excute parent method

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!

like image 230
user2768227 Avatar asked Apr 16 '26 22:04

user2768227


1 Answers

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'>)
like image 191
falsetru Avatar answered Apr 19 '26 12:04

falsetru