简体   繁体   English

更新类的实例属性

[英]Updating instance attributes of class

I have been googling a lot on this topic and I did not really find a commonly accepted way of achieving my goal. 我一直在谷歌搜索这个主题,我没有找到一个普遍接受的方式来实现我的目标。

Suppose we have the following class: 假设我们有以下课程:

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)

and x should be a numpy array! x应该是一个numpy数组! If I run 如果我跑

A = MyClass(x=np.arange(10))
print(A.x)
print(A.length)

I get 我明白了

[0 1 2 3 4 5 6 7 8 9] and 10 . [0 1 2 3 4 5 6 7 8 9]10 So far so good. 到现在为止还挺好。 But if I use the append method 但是如果我使用append方法

A.append(np.arange(5))

I get [0 1 2 3 4 5 6 7 8 9 0 1 2 3 4] and 10 . 我得到[0 1 2 3 4 5 6 7 8 9 0 1 2 3 4]10 This is also expected since the instance attribute length was set during the instantiation of A . 这也是预期的,因为在实例化A期间设置了实例属性length Now I am not sure what the most pythonic way of updating instance attributes is. 现在我不确定更新实例属性的最pythonic方法是什么。 For example I could run __init__ again: 例如,我可以再次运行__init__

A.__init__(A.x)

and then the length attribute will have the correct value, but in some other posts here I found that this is somehow frowned upon. 然后length属性将具有正确的值,但在其他一些帖子中,我发现这有点不受欢迎。 Another solution would be to update the length attribute in the append method directly, but I kind of want to avoid this since I don't want to forget updating an attribute at some point. 另一个解决方案是直接更新append方法中的length属性,但我有点想避免这种情况,因为我不想忘记在某个时候更新属性。 Is there a more pythonic way of updating the length attribute for this class? 有更多pythonic方法更新此类的length属性吗?

Don't update it, just read it when you need it with a getter : 不要更新它,只需在需要时使用getter 读取它:

class MyClass:
    ...

    @property
    def length(self):
        return self.x.size

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM