Toandd Toandd - 27 days ago 10
Python Question

Python multi-instances use the same variable

I want to use a variable for two instances in python.
When a instance update the variable, it also be updated in other instances.

my variable is task_id:

class Task(object): # pragma: no cover

def run_deploy(self, args, **kwargs):
# atexit.register(atexit_handler)
self.task_id = kwargs.get('task_id', str(uuid.uuid4()))

def start_benchmark(self, args, **kwargs):
"""Start a benchmark scenario."""
atexit.register(atexit_handler)

self.task_id = kwargs.get('task_id', str(uuid.uuid4()))


But when I run code, I detected that task_id has different value, I want they have same value.

Please let me know how to do it.
Thanks!

Answer Source

To reference an object in python is trivial. Here is a simple example using a class instance:

class cl:
  var1 = 0
  def __init__(self, var2):
    self.var2 = var2

Lets look at two instances of this class and how they update:

>>> x = cl(1) #
>>> y=x
>>> print(y.var2)
1
>>> y.var2 = 2
>>> print(x.var2)
2

And now comes the crucial part:

>>> x is y
True

Don't forget that ìs is not the same as ==.

The same happens also to var1 for both instances.