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!

6
  • Check if this helps Static Vatiables Commented Feb 27, 2017 at 10:13
  • To understand what happens and how things work in Python, see for example nedbatchelder.com/text/names1.html Commented Feb 27, 2017 at 10:13
  • Can you put some code in so I can see what you want to happen please? Commented Feb 27, 2017 at 10:19
  • I asked a question in following url: stackoverflow.com/questions/42477885/…, you can look at some code in that url. thanks! Commented Feb 27, 2017 at 10:26
  • I edited post @The Stupid Engineer Commented Feb 27, 2017 at 10:47

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.