How to define a method to return an instance of the current class of the wrong class where it was inherited in Python?

I am trying to overload a statement that forces it to return an object of the same instance of the current class, and 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 example, in this case, I would like to return an instance Encycolpedia(not an instance Book) without overloading another time when an operator __add__with the same line with Encyclopediainstead BookI have tried:

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

But that will not work.

What if the Enclcopedia class has a different attribute:

class Encyclopedia(Book):
    def __init__(self,name,pages,color):
        Book.__init__(self,name,pages)
        self.color=color
+4
source share
2 answers

self.__ class__ , . :

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

- , ( , , , - ):

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

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

    def __str__(self):
        classname = self.__class__.__name__
        return '{}({}, {})'.format(classname, self.name, self.pages)

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

    def __add__(self, other):
        tmp = super(Encyclopedia, self).__add__(other)
        return Encyclopedia(tmp.name, tmp.pages, self.color+other.color)

    def __str__(self):
        classname = self.__class__.__name__
        return '{}({!r}, {}, {!r})'.format(classname, self.name, self.pages,
                                         self.color)


a = Encyclopedia('Omina', 234, 'grey')
b = Encyclopedia('Omnia2', 244, 'blue')
ab = a+b
print(ab)  # -> Encyclopedia('Omina', 478, 'greyblue')
+1

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


All Articles