The problem of multiple inheritance in Python!

Why does c.print_a () output 'B'?

class A(object):
    def __init__(self):
        self.some_name = 'A'

    def print_a(self):
        print self.some_name

class B(object):
    def __init__(self):
        self.some_name = 'B'

    def print_b(self):
        print self.some_name

class C(A, B):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)

if __name__ == '__main__':
    c = C()
    c.print_a()

class A(object):
    def __init__(self, some_name='A'):
        self.some_name = some_name

    def print_a(self):
        print self.some_name

class B(object):
    def __init__(self, some_name='B'):
        self.some_name = some_name

    def print_b(self):
        print self.some_name

class C(A, B):
    def __init__(self):
        A.__init__(self, some_name='AAAAA')
        B.__init__(self, some_name='BBBBB')

if __name__ == '__main__':
    c = C()
    c.print_a()
+3
source share
3 answers

Here you have only one object; the property some_nameis divided between methods from all inherited classes. You call A.__init__, which sets it to A, then B.__init__, which changes it to B.

Also note that you are calling the base methods incorrectly; use super:

class A(object):
    def __init__(self):
        self.some_name = 'A'
        super(A, self).__init__()

    def print_a(self):
        print self.some_name

class B(object):
    def __init__(self):
        self.some_name = 'B'
        super(B, self).__init__()

    def print_b(self):
        print self.some_name

class C(A, B):
    def __init__(self):
        super(C, self).__init__()

if __name__ == '__main__':
    c = C()
    c.print_a()
+5
source

self, some_name B.__init__. , ++, , A.some_name B.some_name. Python, .

+1

Suppose you want C to give names for some objects of type A and B and later call some print_a and print_b methods on objects of type C to return these names?

You can get this type of behavior using the C ++ inheritance model, but the python model is very different. Only one object with one set of fields. If you want C ++ behavior, the easiest way is probably to declare subobjects (and this is similar to the usual abuse of inheritance over a composition).

It looks like you are trying to do something like:

class Printable(object):
    def __init__(self, name):
        self.name = name

    def myprint(self):
        print self.name

class C(object):
    def __init__(self):
        self.a = Printable('A')
        self.b = Printable('B')

    def print_a(self):
        self.a.myprint()

    def print_b(self):
        self.a.myprint()

if __name__ == '__main__':
    c = C()
    c.print_a()
+1
source

Source: https://habr.com/ru/post/1785138/


All Articles