更新类的实例属性

Han*_*nah 3 python

我一直在谷歌搜索这个主题,我没有找到一个普遍接受的方法来实现我的目标.

假设我们有以下课程:

import numpy as np
class MyClass:

    def __init__(self, x):
        self.x = x
        self.length = x.size

    def append(self, data):
        self.x = np.append(self.x, data)
Run Code Online (Sandbox Code Playgroud)

并且x应该是一个numpy阵列!如果我跑

A = MyClass(x=np.arange(10))
print(A.x)
print(A.length)
Run Code Online (Sandbox Code Playgroud)

我明白了

[0 1 2 3 4 5 6 7 8 9]10.到现在为止还挺好.但是如果我使用append方法

A.append(np.arange(5))
Run Code Online (Sandbox Code Playgroud)

我得到的[0 1 2 3 4 5 6 7 8 9 0 1 2 3 4]10.这也是预期的,因为实例属性length是在实例化期间设置的A.现在我不确定更新实例属性的最pythonic方法是什么.例如,我可以__init__再次运行:

A.__init__(A.x)
Run Code Online (Sandbox Code Playgroud)

然后该length属性将具有正确的值,但在这里的一些其他帖子中我发现这是不知何故不赞成的.另一个解决方案是直接更新方法中的length属性append,但我有点想避免这种情况,因为我不想忘记在某个时候更新属性.有更多pythonic方法更新length此类的属性吗?

dec*_*eze 7

不要更新它,只需在需要时使用getter 读取它:

class MyClass:
    ...

    @property
    def length(self):
        return self.x.size
Run Code Online (Sandbox Code Playgroud)