Is it possible to declare a class variable that will give the sum of two other class variables

class my_class(object):
    def __init__(self):
        self.ref        = 0
        self.ask        = 0
        self.added      = self.ref + self.ask 

inst = my_class()
inst.ref   = 5
inst.ask   = 7
print(inst.ref + inst.ask)
print(inst.added)

      

I would like print(inst.added)

to return 12, but it returns 0

+3


source to share


3 answers


In fact, the method whose name is __init__

called immediately after the class is created (cf __new__

). This means that when you do

inst = my_class()

      

inst.added

is already equal 0

, whatever you do after.

What you can do is define another method that does what you need, when you need it (and so after instantiation). For example.

class my_class(object):
    def __init__(self):
        self.ref = 0
        self.ask = 0

    @property
    def added(self):
        return self.ref + self.ask

    def add(self):
        return self.ref + self.ask

      

Finally



>>> inst = my_class()
>>> inst.ref = 5
>>> inst.ask = 7
>>> inst.added # briefly, the property decorator does the job of calling the callable for you 
12
>>> inst.add() # while here, you do call the callable
12
>>> inst.ref = 7
>>> inst.added
14
>>> inst.add()
14

      

However, keep in mind that even if you can access added

as a generic attribute, you will get an error if you try to set it directly (in Python 2 as well as version 3), i.e.

>>> inst.added = 15

      

returns the following error

Traceback (most recent call last):
  File "<pyshell#XX>", line YY, in <module>
    inst.added = 15
AttributeError: can't set attribute

      

+1


source


The easiest way is to make a added

method and call it:

>>> class A:
...    def __init__(self):
...       self.ref = 0
...       self.ask = 0
...    def added(self):
...       return self.ref + self.ask
...
>>> a = A()
>>> a.ref = 5
>>> a.ask = 7
>>> a.added()
12
>>>

      



Or, you can make a property added

that allows you to access it as a data attribute instead of a method:

>>> class A:
...    def __init__(self):
...       self.ref = 0
...       self.ask = 0
...    @property
...    def added(self):
...       return self.ref + self.ask
...
>>> a = A()
>>> a.ref = 5
>>> a.ask = 7
>>> a.added
12
>>>

      

+6


source


When you execute self.added = self.ref + self.ask

, this takes the current values self.ref

and self.ask

and adds them together immediately during the execution of that line. self.added

will not update when you change self.ref

or self.ask

. Instead, you need to make a function in your class to set these values:

class my_class(object):
    def __init__(self):
        self.ref        = 0
        self.ask        = 0
        self.added      = self.ref + self.ask 

    def set_ref(self, value):
        self.ref = value
        self.added = self.ref + self.ask

inst = my_class()
inst.set_ref(5)
print(inst.added)

      

0


source







All Articles