【问题标题】:Inheritance error at __str__ function with multiple parameters具有多个参数的 __str__ 函数的继承错误
【发布时间】:2021-05-26 03:21:15
【问题描述】:

我是 python 新手,正在学习多重继承。我对孩子的__str__ 功能有疑问。当我试图编译我的代码时抛出这个错误

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

我的孩子班级是:

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
    

另外一类是:

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

而执行类cuadrado测试的文件是:

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
    

感谢支持!

【问题讨论】:

    标签: python inheritance multiple-inheritance


    【解决方案1】:

    超类不是类实例的属性。

    您只需直接调用超类的方法,将self 作为普通参数传递。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      相关资源
      最近更新 更多