- 1

How do I use a variable declared in one class in another class without using "global" in python3?

Example: class foo: def func1() : a=12 return a class bar: def func2() : b=33 c=a+b ..... I want to use variable a in bar without getting an error that I used the variable before declaring it. I also don't want to use the global statement.

15th Jan 2019, 3:46 PM
Teddy Okello
Teddy Okello - avatar
4 Respuestas
+ 1
Wouldn't this be quite similar to 'global' though, if all the classes and their methods access this one module ad libitum?
16th Jan 2019, 7:01 PM
HonFu
HonFu - avatar
0
Hm... bar.func2 could take an argument. And foo could call the method of bar, passing its a. def foos_method(): bar.func2(self.a) Something like that?
15th Jan 2019, 3:55 PM
HonFu
HonFu - avatar
- 1
After looking at the python docs, I found that you could just create a .py file that contains all your initialized variables. This can then be imported and the variables referenced like a method. [config. py] a b [example. py] import config class foo: def func1(): config.a=12 class bar: def func2(): config.b=33 c=a+b ......
16th Jan 2019, 6:47 PM
Teddy Okello
Teddy Okello - avatar
- 1
I am still trying to make it simpler. Also this allows the variables to be used accross different files. It also removes the nagging flake8 messeges.
16th Jan 2019, 7:04 PM
Teddy Okello
Teddy Okello - avatar