Search code examples
pythonclassobject-oriented-analysis

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.


Solution

  • oh, if this is a function within a class, don't use a global, make it an attribute of the class!

    self.output_dict = {}