总的菜鸟在这里。此示例中有两个python文件。第一个是从github克隆的,第二个是我自己的。第一个称为city_data.py。我的被称为analyzer.py。在city_data.py代码中,有一个带有提示的类,该类中包含许多已定义的函数。在我的analyzer.py文件中,我想在类中运行特定功能。我可以运行该函数(表输出),但是当我尝试从文件中调用变量时,它只会显示“ NameError:未定义名称'pop_dens'”。在导入文件上运行该函数时,是否可以从我的文件中调用变量pop_dens?
city_data.py
class city_stats():
prompt = '> '
def table_output(self, arg):
pop_dens = SingleTable(volume,'city')
...
print(table)
...
analyze.py
from city_data import city_data
analyze = city_stats()
density_output = analyze.table_output("Chicago")
print(pop_dens)
运行analyse.py
table outputs successfully
"NameError: name 'pop_dens' is not defined"
答案 0 :(得分:0)
如果要从另一个类访问变量,请使用class_name.class_variable形式。 根据您的情况
...
print(analyze.pop_dens)
...