1

Is it possible to define an instance variable in a class as a function of another? I haven't gotten it to work unless you redefine the "function instance variable" all the time.

Basically you could have a scenario where you have one instance variable that is a list of integers, and want to have the sum of these as an instance variable, that automatically redefines every time the list is updated.

Is this possible?

class Example:
    list_variable = []
    sum_variable = sum(list_variable)

    def __init__(self, list_variable):
        self.list_variable = list_variable
        return

This will result in sum_variable = 0 unless you change it.

I understand that this is far from a major issue, you could either define sum_variable as a method or redefine it every time you change list_variable, I'm just wondering if it's possible to skip those things/steps.

2

1 Answer 1

4

Python offers the property decorator for a syntatically identical use of your example:

class Example:
    list_variable = []

    def __init__(self, list_variable):
        self.list_variable = list_variable
        return

    @property
    def sum_variable(self):
        return sum(self.list_variable)

e = Example(list_variable=[10, 20, 30])
e.sum_variable  # returns 60
Sign up to request clarification or add additional context in comments.

3 Comments

I was looking at this earlier. The property isn't quite equivalent to the OP's question as Example.list_variable would be [10,20,30] but Example.sum_variable gives a property object. Is there any way of returning Example.sum_variable that would return 3, rather than having to create an instance of Example?
You'd probably have to use something like this: using property on classmethods. That being said, in my code above Example.list_variable would still be [], not [10, 20, 30], because the creation of my instance e does not affect the class variable list_variable - it just overwrites the self.list_variable namespace for that particular instance, and not for the class as a whole.
Good point. Then again, just realised that the post does talk about instance variables, even though the example defines sum_variable as a class variable, so I guess it should answer the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.