在父项中更改后,如何从其他模块访问继承的变量? [英] How do I access inherited variables from another module when they are changed in parent?
问题描述
我有一个文件a.py
I have a file a.py
avariable = None
class a():
def method(self):
global avariable
avariable = 100
print "variable is", avariable
和来自导入的文件b.py
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()
文件 b
从 a
导入所有内容,并且还继承自 a
。
a
的方法
被调用,可用
更改为100但是当我在b中打印 avariable
时,值为无
。如何在课堂上使用 b
变量 avariable
a
班级改变了吗?
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?
输出:
>python b.py
variable is 100
avariable is None
澄清
对我来说,从导入中使用
It's crucial for me to use
from a import *
因为我已经在类b中使用语法
because I have already code in class b that calls methods of class a using the syntax
self.method()
并且无法更改。
ie
from a import *
class b(a):
def mymethod(self):
self.method()
print "avariable is " , avariable
if __name__ == '__main__':
b().mymethod()
那么有没有办法以任何方式访问变量 avariable
而没有前缀 b $ b avariable
?
So is there a way to access the variable avariable
in a without prefixing in any way the
avariable
?
推荐答案
a.py
a.py
avariable = None
class a():
def method(self):
global avariable
avariable = 100
print "variable is", avariable
b.py
b.py
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()
输出:
Output:
None
variable is 100
avariable is 100
variable is 100
avariable is 100
你总是得到无
,因为一旦你导入 avariable
你就把它保存在你自己的文件中,但是 a.py
正在改变,是e 可变的
变量在自己的文件中(或者更合适的是,它自己的全局命名空间),因此,你看不到任何变化。
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.
但在上面的示例中,您可以看到更改。这是因为,我们正在导入 a
模块本身,从而访问其所有对象(Python中的所有内容都是对象)。因此,当我们调用 a.avariable
时,我们实际上是在中调用
的全局命名空间。 avriable
变量a
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()
这篇关于在父项中更改后,如何从其他模块访问继承的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!