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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With