是下面定义的两个类别Point()
和Circle()
:
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
@property
def x(self):
return self._x
@x.setter
def x(self, x):
self._x = x
@property
def y(self):
return self._y
@y.setter
def y(self, y):
self._y = y
def __repr__(self):
return f"{self._x}, {self._y}"
def move(self, x, y):
self._x = x
self._y = y
return self._x, self._y
class Circle:
def __init__(self, radius, x, y):
self._radius = radius
self.x = x
self.y = y
def move(self, x, y):
Point.move(self, x, y)
def __repr__(self):
return f"radius = {self._radius}, \nx = {self.x},\ny = {self.y}"
point1 = Point(12, 3)
print(point1)
point1.y = 0
print(point1)
point1.move(55, 7)
print(point1)
circle1 = Circle(4, 1, 1)
print(circle1)
circle1.move(2, 2)
print(circle1)
我尝试在Circle中开发方法move(x,y)
,但不使用继承从类Point调用方法move(x,y)。首先初始化一个对象:
circle1 = Circle(4,1,1)
但是当您使用circle1.move(2,2)
时,圆的位置仍然是(1,1):怎么了?我想使用_x和_y模拟私有变量!
存在的问题是您没有使用“ composition”-您只是从您的圈子类的方法中随机调用Point.move
。该调用将失败,因为如果放置在其他任何地方,它将失败:Point.move
是一个实例方法,它需要一个point实例才能进行工作。
对于“组合”,您需要具有作为类属性的另一个类的实例,然后在需要时调用这些实例上的方法。
例如,您的“圆”可能具有一个点的“ .center”属性。然后,您只需在实例中调用circle.center.move
-或者,如果您希望在circle类本身中使用.move
方法:
class Circle:
def __init__(self, radius, x, y):
self._radius = radius
self.center = Point(x, y)
def move(self, x, y):
self.center.move(x, y)
def __repr__(self):
return f"Circle center at ({self.point}), radius: {self.radius}"
将Circle
类更改为:
class Circle:
def __init__(self, radius, x, y):
self._radius = radius
self._x = x
self._y = y
def move(self, x, y):
Point.move(self, x, y)
def __repr__(self):
return f"radius = {self._radius}, \nx = {self._x},\ny = {self._y}"
示例
circle1 = Circle(4, 1, 1)
print(circle1)
circle1.move(2, 2)
print(circle1)
输出
radius = 4,
x = 1,
y = 1
radius = 4,
x = 2,
y = 2
否则,当执行Point.move
时,将创建两个新字段(_x, _y
),请参见:
circle1 = Circle(4, 1, 1)
circle1.move(2, 2)
print(circle1._x, circle1._y)
输出
2 2
您没有操纵正确的变量。您圈子的班级使用了self.x
和self.y
,但是在对Point.move(self, x, y)
的调用中,您操纵了self._x
和self._y
来代替