【发布时间】:2020-07-17 16:54:53
【问题描述】:
成为下面定义的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来模拟私有变量!
【问题讨论】:
-
您是否将
circle1.x与circle1._x进行了比较?另外,虽然我认为这只是任意示例代码,但值得指出的是,在 Python 中像这里一样使用属性是一种不好的做法。 -
python 中不需要 setter/getter 函数。这不是 java :)
-
你可能想要
self.center = Point(x, y)而不是self.x = x ; self.y = y -
拥有
property没有任何好处,因为它所做的只是提供对隐藏属性的读/写访问权限。直接使用x和y属性即可。property的要点是,您可以在如果需要添加getter/setter,而不会破坏属性的外观。
标签: python python-3.x oop