0

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!

Toandd
  • 300
  • 1
  • 3
  • 13
  • Check if this helps [Static Vatiables](http://stackoverflow.com/questions/68645/static-class-variables-in-python) – Albatross Feb 27 '17 at 10:13
  • To understand what happens and how things work in Python, see for example https://nedbatchelder.com/text/names1.html – Thierry Lathuille Feb 27 '17 at 10:13
  • Can you put some code in so I can see what you want to happen please? – The Stupid Engineer Feb 27 '17 at 10:19
  • I asked a question in following url: http://stackoverflow.com/questions/42477885/separate-a-python-function-into-two-different-functions, you can look at some code in that url. thanks! – Toandd Feb 27 '17 at 10:26
  • I edited post @The Stupid Engineer – Toandd Feb 27 '17 at 10:47
  • I was going to suggest using a class before seeing your code, but your example is already using a class. You've probably seen the other answer by @prometeu already. This probably gives you what you want? – The Stupid Engineer Feb 27 '17 at 13:12

2 Answers2

3

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.

prometeu
  • 679
  • 1
  • 8
  • 23
1

In python, everything is a reference. A variable is merely a name you give to a reference to an object. You can give many names to refer to the same object.

This pretty much how python works, and it's exactly what you need here.

E.g.:

a = []  # a reference to an empty list, named "a"
b = a   # a reference to the same empty list, named "b"
a.append(5)  # modify, through the "a" reference
print(b)  # "b" still refers to the same list, which is not empty now
=> [5]
shx2
  • 61,779
  • 13
  • 130
  • 153