1

Hello everyone, i have one python script file that creates a moving object therefore its coordinates(of created object that can be sphere , box etc) are changing and i want to use the these changing variable in another file so that both files get the same value of that variable at a specific time. Please tell me that How can i do it. All helps are appreciated. Thanks. Given Below is the code that generates the variable for both files.

zp = 0
def givalue();
        global zp
        if zp > 0.4:
            zp = 0.1
            return zp
        else:
            zp = zp + 0.1
            return zp
while 1:
    z = givalue()
    print 'value of zp is ', z
Paras
  • 240
  • 1
  • 13
  • 2
    Possible duplicate of [Using global variables between files?](https://stackoverflow.com/questions/13034496/using-global-variables-between-files) – Sadjad Anzabi Zadeh Apr 17 '18 at 12:57

1 Answers1

0

Sharing values through global variables in files is generally not considered as a correct design. It is much more powerful and flexible to create a base class storing the shared data and a arbitrary number of derived classes that need access to this shared data. Here is a skeleton for that pattern:

class Shared(object):
  shared = [0, 0] # put all shared values in a list or a dictionary

class C1(Shared):
  def __init__(self):
    print('C1: shared =', self.shared)
  def update(self, index):
    self.shared[index] += 1
    print('C1: shared =', self.shared)

class C2(Shared):
  def __init__(self):
    print('C2: shared =', self.shared)
  def update(self, index):
    self.shared[index] += 1
    print('C2: shared =', self.shared)

c1 = C1()
c1.update(0)
c2 = C2()
c2.update(0)
c2.update(1)
c1.update(1)

Result:

C1: shared = [0, 0]
C1: shared = [1, 0]
C2: shared = [1, 0]
C2: shared = [2, 0]
C2: shared = [2, 1]
C1: shared = [2, 2]

Of course all three classes may be in three different source files, just import before using them

If you REALLY insist on not using the OO paradigm, the following code may fulfil your wishes:

# --------------
# shared.py
# --------------
shared = [0,0] # put all shared values in a list or a dictionary

# --------------
# C1.py
# --------------
from shared import *
print('C1: shared =', shared)
shared[0] += 1
print('C1: shared =', shared)

# --------------
# C2.py
# --------------
from shared import *
print('C2: shared =', shared)
shared[0] += 1
print('C2: shared =', shared)

The magic works from the fact that an imported file is only executed when it is imported for the first time, so the shared variable will not be reset when shared.py is imported the second time.

sciroccorics
  • 2,357
  • 1
  • 8
  • 21
  • Thank you very much for you help. my problem was solved as i made simple functions and called them in the other file and used the break statement because both files had infinite while loop. – Muhammad Bilal Abbasi Apr 23 '18 at 14:57