动态@property方法有什么缺点吗?

我有一个python类,而不使用以下结构:

def __init__(self):
    self._set_a()

def _set_a(self):
    self.a = 1

>>> instance.a
1

我正在使用以下结构:

def __init__(self):
    pass

@property
def a(self)
    try:
        return self._a
    except AttributeError:
        self._a = 1
        return self._a

>>> instance.a
1

在这个简单的示例中,我认识到潜在的丑陋代码库的缺点,尽管这是主观的。

The advantage (particularly if a is an intensive calculation) is that the instance can be created immediately and (for many of these complex attributes) they become available and stored dynamically only as needed on the instance.

如果有任何已知或假设的原因可能不支持第二种模式,我很感兴趣。

For example if I have to call instance.a many times through an iterative process would the codebase suffer?

评论