如何将子类的数据属性分配给其父类的属性



我有一个类Rectangle,它的数据属性为width和height,我想要一个子类Square,其数据属性为side_length。

我该怎么做才能使正方形宽度和正方形高度给出它的边长?即与方形侧面相同

class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
class Square(Rectangle):
def __init__(self, side)
self.side = side

这就是我到目前为止所拥有的。

您可以调用Rectangle的构造函数。

super(Square,self).__init__(side, side)

或者您可以使用属性来返回这些属性。我会接近超级。

@property
def length(self):
return self.side
@property
def width(self):
return self.side

如果在创建对象后可以更改sideheightwidth属性,情况会变得更加复杂。您需要保持widthheight同步一致。一种可能的方法是完全取消side作为Square上的存储属性,而是将其作为更新Rectangle的宽度和高度的读写属性。

在初始构造函数之后保持高度/宽度/侧面排序:


class Rectangle:
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
def __repr__(self):
return(f"{self.__class__.__name__}:{self.height=} {self.width=}")
def __init__(self, height, width):
self.height = height
self.width = width
class Square(Rectangle):
def __repr__(self):
return(f"{self.__class__.__name__}:{self.side=}")
@property
def side(self):
return self._width
@side.setter
def side(self, value):
self._width = value
self._height = value
def __init__(self, side):
super(Square, self).__init__(side, side)
#these are here so you can't cheat and vary height and width
#independently on a square
@property
def width(self):
return self.side
@width.setter
def width(self, value):
self.side = value
@property
def height(self):
return self._side
@height.setter
def height(self, value):
self.side = value

rectangle = Rectangle(5,2)
print(rectangle)
rectangle.height = 6
print(rectangle)
square = Square(3)
print(square)
square.side = 6
print(square)
square.height = 9
print(square)

输出:

$ py test_square.py
Rectangle:self.height=5 self.width=2
Rectangle:self.height=6 self.width=2
Square:self.side=3
Square:self.side=6
Square:self.side=9

最新更新