python - Updating instance attributes of class -


i have been googling lot on topic , did not find commonly accepted way of achieving goal.

suppose have following class:

import numpy 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 numpy array! if 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] , 10. far good. if use append method

a.append(np.arange(5)) 

i [0 1 2 3 4 5 6 7 8 9 0 1 2 3 4] , 10. expected since instance attribute length set during instantiation of a. not sure pythonic way of updating instance attributes is. example run __init__ again:

a.__init__(a.x) 

and length attribute have correct value, in other posts here found somehow frowned upon. solution update length attribute in append method directly, kind of want avoid since don't want forget updating attribute @ point. there more pythonic way of updating length attribute class?

don't update it, read when need a getter:

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

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -