Search code examples
pythoninheritancemultiple-inheritance

Inheritance error at __str__ function with multiple parameters


I am new on python and I am learning multiple inheritance. I have a issue on __str__ function of the child. When I tried to compile my code throw this error

return self.FiguraGeometrica.__str__() + self.Color.__str__() + str(self.area())
AttributeError: 'Cuadrado' object has no attribute 'FiguraGeometrica'

My child class is:

from figura_geometrica import FiguraGeometrica
from color import Color

class Cuadrado(FiguraGeometrica, Color):
    def __init__(self, lado, color):
        FiguraGeometrica.__init__(self, lado, lado)
        Color.__init__(self, color)
    
    def __str__(self):
        return self.FiguraGeometrica.__str__() + self.Color.__str__() + str(self.area())
    
    def area(self):
        return self.alto * self.ancho
    

And the other class are:

class FiguraGeometrica:
    def __init__(self, ancho, alto):
        self.__ancho = ancho
        self.__alto = alto
    
    def __str__(self):
        return "Ancho: " + str(self.__ancho) + ", alto: " + str(self.__alto)
    
    def get_ancho(self):
        return self.__ancho
    
    def set_ancho(self, ancho):
        self.__ancho = ancho
    
    def get_alto(self):
        return self.__alto
    
    def set_alto(self, alto):
        self.__alto = alto
class Color:
    def __init__(self, color):
        self.__color = color
        
    def __str__(self):
        return "Color: " + str(self.__color)
    
    def get_color(self):
        return self.__color
    
    def set_color(self, color):
        self.__color = color

And the file that execute a test of class cuadrado is:

from figura_geometrica import FiguraGeometrica
from color import Color

class Cuadrado(FiguraGeometrica, Color):
    def __init__(self, lado, color):
        FiguraGeometrica.__init__(self, lado, lado)
        Color.__init__(self, color)
    
    def __str__(self):
        return self.FiguraGeometrica.__str__() + self.Color.__str__() + str(self.area())
    
    def area(self):
        return self.alto * self.ancho
    

Thanks for the support!


Solution

  • Superclasses are not attributes of class instances.

    You just call the superclass's method directly, passing self as an ordinary argument.

        def __str__(self):
            return FiguraGeometrica.__str__(self) + Color.__str__(self) + str(self.area())