【发布时间】: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