1

e.g. f1.py (simplified):

...
class TestClass:
    x = 0

...

and f2.py :

from f1 import *
tc = TestClass()

tc.x = 73

and f3.py :

from f1 import *
...
print(tc.x)
...

Of course this is wrong, but how to do it right? Well, I simply need access to data and functions in the same instance of a class from different files, comparable to e.g. 'extern' in C. Generating a new instance in every file will generate different variables, is therefore not applicable. Thanks for help.

7
  • Now here is an example of too little code. What is really in f3.py which wants to access tc.x? Commented Sep 13, 2020 at 20:44
  • 1
    is there a reason you can't import f2 instead of f1 in f3? Commented Sep 13, 2020 at 20:51
  • 1
    while it's not particularly clear what you're trying to do, if as it appears you want a "singleton" instance then why not just puttc = TestClass() at the bottom of f1.py and simply import that in the other files, rather than the class itself? (Unfortunately Python does not allow you to choose not to export the class, as many other languages do.) Commented Sep 13, 2020 at 20:51
  • Thanks; comments and answers helped me to understand. So I use the easier and sufficient method with tc = TestClass() in f1.py and import f1 to other files where needed. Thanks for the fast help Commented Sep 15, 2020 at 11:08
  • @quamrana: The project consists because of its size about 10 different files, most of them with access to data and methods of the same class. I like to use classes to make modules better portable. Maybe I went a bit too far in reducing the description, f3.py is a placeholder for more files with the same functionality. Commented Sep 15, 2020 at 11:19

2 Answers 2

2

Just import f2.py:

from f2 import tc
...
print(tc.x)
...
Sign up to request clarification or add additional context in comments.

Comments

1

You should be using a singleton class as your TestClass. Following is a link with pattern implementation in python that you can follow. https://www.tutorialspoint.com/python_design_patterns/python_design_patterns_singleton.htm

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.