Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a method so that return the instance of the current class not of the class where it was inherited in Python?

I am trying Overloading an operator forcing it to return an object of the same instance of the current class not the parent class where the method was overloaded.

class Book:
    def __init__(self,name,pages):
        self.name=name
        self.pages=pages

    def __add__(self,other):
        return Book(self.name,(self.pages + other.pages))


class Encyclopedia(Book):
    def __init__(self,name,pages):
        Book.__init__(self,name,pages)


a=Encyclopedia('Omina',234)
b=Encyclopedia('Omnia2',244)
ab=a+b
print ab

Out: <__main__.Book instance at 0x1046dfd88>

For instance in this case I would like to return an Encycolpedia instance (not a Book instance) without overloading another time the operator __add__ with the same line with Encyclopedia instead of Book I have tried:

return self(self.name,(self.pages + other.pages))

But it doesn't work.

What if the Class Enclcopedia has another attribute:

class Encyclopedia(Book):
    def __init__(self,name,pages,color):
        Book.__init__(self,name,pages)
        self.color=color
like image 673
G M Avatar asked Mar 13 '23 05:03

G M


1 Answers

You could utilize self.__class__ instead of casting to Book. Your original add function should look like:

def __add__(self,other):
    return self.__class__(self.name,(self.pages + other.pages))
like image 65
Jacob H Avatar answered Apr 30 '23 15:04

Jacob H