0

I have two inherited classes in another class

Class A(object):
    def printhello(self):
        self.message1="hello"
Class B(object):
    def printbye(self):
        self.message2="bye"
Class C(A,B):
    def __init__(self):
        super(C,self).printhello()
    def printboth(self):
        print(self.message1)
        print(self.message2)

a = A()
b = B()
c = C()

c.printboth()

How do I super both A and B?, note this is just an example code.

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by pyTony
0

For this case, you would use the alternate method calling syntax, using the class name instead of the object name, and passing the self argument explicitly:

class.method(self, args)

This isn't specific to inherited methods; it could be used anywhere you have a method call. It's uncommon to use it for an ordinary method invocation because it is a bit confusing, but it can be done.

class A(object):
    def printhello(self):
        self.message1="hello"
class B(object):
    def printbye(self):
        self.message2="bye"
class C(A,B):
    def __init__(self):
        A.printhello(self)
        B.printbye(self)
    def printboth(self):
        print(self.message1)
        print(self.message2)

a = A()
b = B()
c = C()

c.printboth()

Mind you, this probably isn't the typical approach to this; a more Pythonic way might be:

class A(object):
    def __init__(self):
        self.message1="hello"

    def __str__(self):
        return self.message1

class B(object):
    def __init__(self):
        self.message2="bye"

    def __str__(self):
        return self.message2

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

    def __str__(self):
        return A.__str__(self) + '\n' + B.__str__(self)

a = A()
b = B()
c = C()

print(c)

But that's neither here nor there.

Edited by Schol-R-LEA

0

For me it is confusing to call funciton printbye, when it only sets one instance variable.

I would try something like this, which delegates the messages to message attribute

class MessageObject(object):
    def __init__(self, message):
        self.message = message
        self.__name__ = 'MessageObject'

    def __str__(self):
        return str(self.message)

    def __repr__(self):
        return '%s(%r)' % (self.__name__, self.message)

class MultiMessageObject(MessageObject):
    def __init__(self, *messages):
        self.__name__ = 'MultiMessageObject'
        self.message = [MessageObject(message) for message in messages]


c = MultiMessageObject('Hello', 'Bye')

print(c)
print(repr(c))

Edited by pyTony

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.