2

Very often my classes have a few attributes, and other object's properties depend on those. What is the best way to define and access those? A minimal example should explain what I'm asking.

Say that I have a class that defines a circle:

class Circle:
    def __init__(self, r):
        self.r = r

Now this circle is instantiated just based on the radius, but I may want to be able to access its diameter, these are the possibilities I see:

A) create a new attribute when instantiating

class Circle:
    def __init__(self, r):
        self.r = r
        self.d = 2*r

B) define a function that returns the diameter

class Circle:
    def __init__(self, r):
        self.r = r
    def d(self):
        d = 2*r
        return d

Solution A does not ensure consistency, if the user changes r, d is not automatically updated, and the mistake can be hard to track down. Solution B requires the user to call a function rather than accessing an attribute. And every time the attribute d has to be accessed, it has to be recalculated, and in general it might be time consuming.

Is there a solution C that ensures consistency and does not require the class user to recalculate the attribute every time it is accessed?

4

1 回答 1

1

您可以在此处使用 Python 属性。

这是文档中对内置属性函数的讨论:

http://docs.python.org/2/library/functions.html#property

在您的情况下,您可以按如下方式使用它:

def getdiameter(self):
    return self.r * 2

def setdiameter(self, d):
    self.r = d / 2

d = property(getdiameter, setdiameter)

您可能希望 d 是只读的(它纯粹是半径的函数)。在这种情况下,您可以从属性中省略 setdiameter 函数。

更新 如果 d 的计算成本非常高,那么我将在第一次读取 d 时计算 d,并在计算 r 时使 d 无效。

def setr(self, r):
    self.r = r
    self.d = None

def getd(self):
    if not self.d is None:
        return self.d
    self.d = self.r * 2 # Our expensive calculation
    return self.d
于 2013-10-24T23:08:36.597 回答