python - 将类的属性和确定它的方法分开是否可以/pythonic?

标签 python class

我希望以前没有人问过这个问题,我的 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/

相关文章:

python - 你如何在 Python 中使用 numpy 处理自然日志(例如 "ln()")?

Python cx_Oracle 缺少 SELECT 关键字

python - 如何在 Python 中使用正则表达式搜索奇怪的非 ASCII 字符?

python - Django,为什么我的 jquery url View 重复?

python - 检测峰宽的稳健算法

Python 类继承函数并从 Child 传递参数

c++ - 什么是类中的类型定义?

c++ - 如何从派生类访问基类中的重载运算符?

c++ - 直接从另一个类实例化时成员整数发生变化

c++ - C++调用抽象基类的构造函数