我希望以前没有人问过这个问题,我的 google/SX-fu 在这个问题上不是很好,因为我可能不知道正确的关键字。
假设我有一个类代表一个相当复杂的对象,例如。 G。具有某些属性(长度、体积...)的点云。通常,我会着手为点云(或在本例中为矩形)定义一个类,如下所示(示例由 A Beginner's Python Tutorial 提供,已修改):
class Rectangle:
def __init__(self,x,y):
self.x = x
self.y = y
def area(self):
return self.x * self.y
def perimeter(self):
return 2 * self.x + 2 * self.y
每当我需要知道矩形的面积时,我只需调用 my_rectangle.area()
,它总是会给我正确的结果,即使矩形的尺寸发生变化。
现在在我的应用程序中,计算周长或面积要复杂得多并且需要花费大量时间。此外,通常,我需要比修改对象更频繁地了解周长。因此,将计算与访问值本身分开是有意义的:
class Rectangle:
def __init__(self,x,y):
self.x = x
self.y = y
def calc_area(self):
self.area = self.x * self.y
def calc_perimeter(self):
self.perimeter = 2 * self.x + 2 * self.y
现在,如果我需要知道矩形的面积,我需要在任何修改后至少调用一次 my_rectangle.calc_area()
,但之后我总能得到 my_rectangle .区域
.
这是个好主意还是我应该将面积计算保留在 .area()
方法中并在需要时访问它,同时将当前面积存储在任何脚本的局部变量中正在使用我的 Rectangle
类吗?
如果这过于基于意见或过于依赖实际应用,请就如何改进问题提出建议。
最佳答案
属性确实是去这里的方法。我会提出以下建议:
class Rectangle:
def __init__(self, x, y):
# member names starting with underscore indicate private access
self._x = x
self._y = y
# it's good practice to initialize all members in __init__
self._area = None
@property
def area(self):
# this is a read-only property.
# access it like:
# rect = Rectangle(1, 1)
# print(rect.area)
# note the missing parentheses.
if self._area is None:
# lengthy computation here, but only when needed
self._area = self._x * self._y
return self._area
@property
def x(self):
# getter for self._x
return self._x
@x.setter
def x(self, value):
# setter for self._x
self._x = value
# invalidate self._area - it will get recalculated on next access
self._area = None
# getters and setters for y are similar.
关于python - 将类的属性和确定它的方法分开是否可以/pythonic?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44756768/