简体   繁体   中英

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. I know the functions work properly, but I can't figure out how to make them work in my class definition.

哦,如果这是类中的函数,请不要使用全局变量,而应将其设为类的属性!

self.output_dict = {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM