I have a file a.py
avariable = None
class a():
def method(self):
global avariable
avariable = 100
print "variable is", avariable
and a file b.py
from a import *
class b(a,):
def mymethod(self):
a().method()
print "avariable is " , avariable
if __name__ == '__main__':
b().mymethod()
File b
imports everything from a
and also inherits from a
.
a
's method
is called and the avariable
is change to 100 but when I print avariable
in b the value is None
. How to I use in class b
the variable avariable
that a
class changed?
Output:
>python b.py
variable is 100
avariable is None
Clarification
It's crucial for me to use
from a import *
because I have already code in class b that calls methods of class a using the syntax
self.method()
and that cannot change.
i.e.
from a import *
class b(a):
def mymethod(self):
self.method()
print "avariable is " , avariable
if __name__ == '__main__':
b().mymethod()
So is there a way to access the variable avariable
in a without prefixing in any way the
avariable
?
avariable = None
class a():
def method(self):
global avariable
avariable = 100
print "variable is", avariable
import a
class b(a.a):
def mymethod(self):
a.a().method()
print "avariable is ", a.avariable
if __name__ == '__main__':
print a.avariable
b().mymethod()
b().mymethod()
None
variable is 100
avariable is 100
variable is 100
avariable is 100
You get None
all the time because once you import avariable
you keep it in your own file, but what a.py
is changing, is the avariable
variable in its own file (or more appropriately, its own global namespace), and thus, you can see no change.
But in the example above, you can see the changes. This is because, we are importing the a
module itself, and thus accessing all its objects (everything in Python is an object). And thus, when we call a.avariable
we are actually calling the avriable
variable in a
's global namespace.
The code below will still produce the same output.
import a
class b(a.a):
def mymethod(self):
self.method()
print "avariable is ", a.avariable
if __name__ == '__main__':
print a.avariable
b().mymethod()
b().mymethod()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With