As I said in this comment, which I will expand on here, if OP wants to be able to change X._CON
on the fly, even after instantiating x = X(var)
and without writing a new class then one way might be to make y
a property and var
an instance attribute like this:
class X(object):
_CON = 0
def __init__(self, var):
self.var = var
@property
def y(self):
return self.var * X._CON
then ...
>>> x = X(2)
>>> x.y # returns 0
>>> X._CON = 3
>>> x.y # returns 6
N.B.: As others have indicated and I think the OP has already discovered, this example uses the class attribute X._CON
and changes to a class attribute will affect all instances of that class. For example, executing the following after instantiating x = X(var)
from above, the value of X._CON
will still be 3; it will not be 0.
Please pay very careful attention to the difference between capital X
the class and little x
the instance in the examples below:
>>> x._CON = 23 # <-- doesn't affect x.y b/c x.y = x.var * X._CON
>>> x.y # still returns 6 b/c X._CON = 3 still
>>> x10 = X(10)
>>> x10.y # returns 30 b/c X._CON = 3
>>> x._CON # returns 23
>>> x10._CON # returns 3 since we changed X._CON to 3
>>> X._CON # returns 3 <-- this is the **class** attribute
Therefore if you want the value of _CON
to be particular to each instance then use self._CON
instead of X._CON
. Starting afresh ...
class X(object):
_CON = 0
def __init__(self, var):
self.var = var
@property
def y(self):
return self.var * self._CON # <-- use **instance** attribute
then ...
>>> x = X(2)
>>> x.y # returns 0
>>> x._CON = 3 # <-- use **instance** attribute
>>> x.y # returns 6
>>> x10 = X(10)
>>> x10.y # returns 0 b/c x10._CON = X._CON = 0
>>> x10._CON = 7 # <-- use **instance** attribute
>>> x10.y # returns 70
>>> x._CON # returns 3
>>> x10._CON # returns 7
>>> X._CON # returns 0
There are a few more variations, like what happens to the instance attributes x._CON
and x10._CON
in the 2nd example using self._CON
if you change the class attribute X._CON
either before or after setting the instance attributes x._CON
or x10._CON
. I'll leave those examples for the reader to explore.