I have a class which has multiple attributes that are related, for example:
class SomeClass:
def __init__(self, n=0):
self.list = range(n)
self.listsquare = [ x**2 for x in self.list ]
If I make an object normally that would no problem, with
a = SomeClass(10)
I will get 2 lists, a.list
and a.listsquare
.
Now if I want to make a empty object first, and assign one attribute to it, I want the other attributes to be automatically updated, for example if I do
b = SomeClass()
b.list = range(5,10)
I want b.listsquare
to be automatically updated, and also the other way around (assign b.listsquare
and auto update b.list
). Is this possible? Is Class the right choice for this?
Thanks to you all, but I'm completely overwhelmed by all the different answers. Can anyone give a complete solution so I can learn write my own?
I would like to achieve a class Foo
with 3 attributes length
, list
and listsquare
such that:
- If I do
a = Foo(3)
, I geta.length = 3
,a.list = [0, 1, 2]
,a.listsquare = [0, 1, 4]
. - If I do
b = Foo().list = [5, 6]
, I getb.length = 2
,b.listsquare = [25, 36]
. - If I do
c = Foo().listsquare = [4, 9]
, I getc.length = 2
,c.list = [2, 3]
.