LINUX.ORG.RU

[python] [множ. наследование] Почему так?

 


0

0

Есть базовый класс и два производных класса.
Первый производный класс не имеет собственной реализации foo
(наследует из базового), второй - имеет.
При множественном наследовании в случае old-style классов
используется foo базового класса (из c1)
В случае new-style - из c2.

Почему так?

# 1
class b:
    def foo(self):
        print('b')
class c1(b):
    pass
class c2(b):
    def foo(self):
        print('c2')
class c(c1, c2):
    pass
cc=c()
cc.foo() # выводит b

# 2
class b(object):
    def foo(self):
        print('b')
class c1(b):
    pass
class c2(b):
    def foo(self):
        print('c2')
class c(c1, c2):
    pass
cc=c()
cc.foo() # выводит c2


http://docs.python.org/tut/node11.html

For old-style classes, the only rule is depth-first, left-to-right. Thus, if an attribute is not found in DerivedClassName, it is searched in Base1, then (recursively) in the base classes of Base1, and only if it is not found there, it is searched in Base2, and so on.

For new-style classes, the method resolution order changes dynamically to support cooperative calls to super(). This approach is known in some other multiple-inheritance languages as call-next-method and is more powerful than the super call found in single-inheritance languages.

kondor ★★★
()
Ответ на: комментарий от anonymous

Ага, понятно.

> А вообще про old-style classes пора забыть. В python 3.0 их уже нет.

Вот поэтому и возник вопрос. Вылезла эта фича при переносе программы на 3.0 :)

mnt
() автор топика
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.