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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
LegendWK
  • 184
  • 9
  • 2
    Possible duplicate of [Real world example about how to use property feature in python?](https://stackoverflow.com/questions/6304040/real-world-example-about-how-to-use-property-feature-in-python) – mkrieger1 Nov 26 '19 at 15:57
  • `sum_variable` could be a `property` that is calculated from `list_variable` (possibly also cached) when it is accessed. – mkrieger1 Nov 26 '19 at 15:57

1 Answers1

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
jfaccioni
  • 7,099
  • 1
  • 9
  • 25
  • 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`? – David Buck Nov 26 '19 at 16:46
  • You'd probably have to use something like this: [using property on classmethods](https://stackoverflow.com/questions/128573/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. – jfaccioni Nov 26 '19 at 17:00
  • 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. – David Buck Nov 26 '19 at 17:12