gpt4 book ai didi

python - python 如何使用类调用其他文件中的变量?

转载 作者:太空宇宙 更新时间:2023-11-03 14:56:51 24 4
gpt4 key购买 nike

大家好,我想知道如何从其他 python 文件调用变量(位于类内部)。我知道执行此操作的波纹管方法,但是如果从原始文件调用该类,它将不起作用。

 from (insert_file_name_hear) import *

这与我正在使用的示例类似:

函数.py

 num = 0
num2 = 0

class Test():

def alt_num(self):
global alt_num
alt = 55

def change(self):
global num, num2
num += alt_num
num2 = num

def print_num():
global num2
print(num2)

def work():
Test.alt_num(Test)
Test.change(Test)
print_num()

打印.py

from functions import *

work()

def printing():
print(num2)

printing()

当我运行 print.py 时,它会准确地在functions.py 文件中打印,但是它会在print.py 文件中打印0。注意:这两个文件位于同一文件夹中,我在 Python 3 中运行它。

谢谢

最佳答案

您可以使用类变量来代替全局变量

函数.py

class Test():
num = 0
num2 = 0
alt = 0

@classmethod
def alt_num(cls):
cls.alt = 55

@classmethod
def change(cls):
cls.num += cls.alt
cls.num2 = cls.num


def print_num():
print(Test.num2)

def work():
Test.alt_num()
Test.change()
print_num()
Test.change()
print_num()
Test.change()
print_num()
return Test.num2

打印.py

from functions import *

work()

def printing():
print(Test.num2)

printing()

注意:上面的输出是

55

110

165

165

前三个来自work(),最后一个来自printing()

关于python - python 如何使用类调用其他文件中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45483749/

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