HansSnah
HansSnah

Reputation: 2270

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! 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. So far so good. But if I use the append method

A.append(np.arange(5))

I get [0 1 2 3 4 5 6 7 8 9 0 1 2 3 4] and 10. This is also expected since the instance attribute length was set during the instantiation of A. Now I am not sure what the most pythonic way of updating instance attributes is. For example I could run __init__ again:

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. 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. Is there a more pythonic way of updating the length attribute for this class?

Upvotes: 3

Views: 305

Answers (1)

deceze
deceze

Reputation: 522626

Don't update it, just read it when you need it with a getter:

class MyClass:
    ...

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

Upvotes: 7

Related Questions