gpt4 book ai didi

python - 当它们在父级中更改时,如何访问从另一个模块继承的变量?

转载 作者:太空狗 更新时间:2023-10-30 02:20:58 26 4
gpt4 key购买 nike

我有一个文件a.py

avariable = None

class a():

def method(self):
global avariable
avariable = 100
print "variable is", avariable

和一个文件b.py

from a import *

class b(a,):

def mymethod(self):
a().method()
print "avariable is " , avariable

if __name__ == '__main__':
b().mymethod()

文件 ba 导入所有内容,也从 a 继承。amethod 被调用并且 avariable 更改为 100 但是当我在 b 中打印 avariable 值时是。如何在 b 类中使用 a 类更改的变量 avariable

输出:

>python b.py 
variable is 100
avariable is None

澄清

对我来说至关重要

from a import *

因为我已经在类 b 中编写了使用语法调用类 a 的方法的代码

self.method()

这不能改变。

from a import *
class b(a):

def mymethod(self):
self.method()
print "avariable is " , avariable

if __name__ == '__main__':
b().mymethod()

那么有没有一种方法可以在没有前缀的情况下以任何方式访问变量avariable变量?

最佳答案

a.py

avariable = None

class a():

def method(self):
global avariable
avariable = 100
print "variable is", avariable

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()

输出:

None
variable is 100
avariable is 100
variable is 100
avariable is 100

你一直得到 None 因为一旦你导入 avariable 你就把它保存在你自己的文件中,但是 a.py 正在改变, 是它自己文件中的 avariable 变量(或者更恰本地说,它自己的全局命名空间),因此,您看不到任何变化。

但是在上面的例子中,你可以看到变化。这是因为,我们正在导入 a 模块本身,从而访问它的所有对象(Python 中的一切都是对象)。因此,当我们调用 a.avariable 时,我们实际上是在调用 a 的全局命名空间中的 avriable 变量。

编辑

下面的代码仍然会产生相同的输出。

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()

关于python - 当它们在父级中更改时,如何访问从另一个模块继承的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19358582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com