p99will
p99will

Reputation: 250

How can I set a variable within a class to include another variable and update when the other value changes?

I find it kind of hard to explain so this is what I mean:

>>> class a(object):
    a = 'z'
    b = 'b'
    c = 'c'
    all = a,b,c


>>> print a.all
('z', 'b', 'c')
>>> a.a = 'a'
>>> print a.a
a
>>> print a.all
('z', 'b', 'c')

How can I make a.all to be accurate to what is in the class I want a.all to be ('a','b','c')

I think this is because when creating a class the values are set then and there. But I think I may need to just set the 'all' value each time i wish to access it, I just don't want to have to type out all the variables' name. This is being applied in a class with over 20 variables.

Or perhaps someone would know an efficient way to reset the 'all' variable with a function.

Upvotes: 0

Views: 97

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121624

Make all a property:

class A(object):
    a = 'z'
    b = 'b'
    c = 'c'

    @property
    def all(self):
        return (self.a, self.b, self.c)

Note that you have to create an instance of the class for this to work:

>>> a = A()
>>> a.all
('z', 'b', 'c')
>>> a.a = 'a'
>>> a.all
('a', 'b', 'c')

Upvotes: 4

Liteye
Liteye

Reputation: 2801

One solution with @property:

class a(object):
    a = 'z'
    b = 'b'
    c = 'c'

    @property
    def all(self):
        return self.a, self.b, self.c

A = a()

print A.all

a.a = 'a'
print A.all

@property needs an instance instead of class.

Upvotes: 3

Related Questions