[英]Global definition in python classes
I'm writing a class to analyze some data. 我正在写一个类来分析一些数据。 One of my functions creates a dict to store the results:
我的函数之一创建了一个字典来存储结果:
def get_top_hits(self):
global output_dict
output_dict = {}
with open(self.all_employees)as file:
employees_data = csv.reader(file, delimiter=';', quotechar='|')
result = [row for row in employees_data]
result.pop(0)
for row in result:
name = row[0]
job = row[1]
number = row[2]
output_dict.setdefault(name, set()).add(job)
return output_dict
However, when I try to access output_dict with another function inside the class definition, Python tells me output_dict is not defined. 但是,当我尝试使用类定义内的另一个函数访问output_dict时,Python告诉我未定义output_dict。 I know the functions work properly, but I can't figure out how to make them work in my class definition.
我知道函数可以正常工作,但是我无法弄清楚如何使它们在我的类定义中起作用。
哦,如果这是类中的函数,请不要使用全局变量,而应将其设为类的属性!
self.output_dict = {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.