【问题标题】:Subclass is not inheriting the attributes of second Super Class子类没有继承第二个超类的属性
【发布时间】:2019-07-27 11:43:33
【问题描述】:

我创建了两个超类 Polygon 和 Shape。我创建了一个子类 Rectangle 来继承这两个类的属性。 Rectangle 类对象可以从 Polygon 类访问属性,但不能从 Shape 类访问。请帮忙

这适用于 python 3。我尝试删除“Shape”类,效果很好。它没有继承 Shape 类

多边形.py

class Polygon:
    __width = None
    __height = None

    def setvalues(self, height, width):
        self.__height = height
        self.__width = width

    def getheight(self):
        return self.__height

    def getwidth(self):
        return self.__width

形状.py

class Shape:
    __colour = None

def set_colour(self, colour):
    self.__colour = colour

def get_colour(self):
    return self.__colour

矩形.py

from polygon import Polygon
from shape import Shape

class Rectangle(Polygon, Shape):
    def GetRectArea(self, height, width):
        Obj1 = Polygon()
        Obj1.setvalues(height, width)
        return Obj1.getheight() * Obj1.getwidth()

    def GetRecttcolour(self):
        Obj1 = Shape()
        Obj1.set_colour('Red')
        return self.get_colour()

main.py

from rectangle import Rectangle 

rect1 = Rectangle()
tri1 = Triangle()

print(rect1.GetRectArea(10, 20))
print(rect1.GetRecttcolour()())

我期待

的输出
200  
'Red'

但我明白了:

200  
Traceback (most recent call last):
  File "G:\Python\Workspace\Python OOP concepts\MultipleInheritnce.py", line 11, in <module>
    print(rect1.GetRecttcolour()())
  File "G:\Python\Workspace\Python OOP concepts\rectangle.py", line 21, in GetRecttcolour
    Obj1.set_colour('Red')
AttributeError: 'Shape' object has no attribute 'set_colour'

【问题讨论】:

  • 如果您需要某个字段的 getter/setter,请使用 property
  • 这是您的代码的实际缩进吗? IE。 set_colour 是否与 class Shape 处于同一级别?

标签: python-3.x multiple-inheritance


【解决方案1】:

GetRectArea方法中做同样的事情:

class Rectangle(Polygon, Shape):

  def GetRectArea(self, height, width):
      Obj1 = Polygon()
      Obj1.setvalues(height, width)
      return Obj1.getheight() * Obj1.getwidth()

  def GetRecttcolour(self):
      Obj1 = Shape()
      Obj1.set_colour('Red')
      return Obj1.get_colour()

当调用GetRecttcolour方法时,它会给你想要的输出'200'和'Red':

rect1 = Rectangle()

print(rect1.GetRectArea(10, 20))
print(rect1.GetRecttcolour())

但是如果你想使用 getter 和 setter 你有属性装饰器,在这里你可以找到关于它们如何工作的很好的解释:How does the @property decorator work?

此外,如果您想查看 MRO(在父类中查找方法时搜索基类的层次结构),请使用内置函数 help(Rectangle),您将获得很多有用的信息:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2023-03-23
    • 1970-01-01
    • 2016-02-09
    • 2022-12-18
    • 2016-10-17
    相关资源
    最近更新 更多