简体   繁体   中英

Trying to figure out how to pass variables from one class to another in python while calling a class from a dictionary

So I am getting used to working with OOP in python, it has been a bumpy road but so far things seem to be working. I have, however hit a snag and i cannot seem to figure this out. here is the premise.

I call a class and pass 2 variables to it, a report and location. From there, I need to take the location variable, pass it to a database and get a list of filters it is supposed to run through, and this is done through a dictionary call. Finally, once that dictionary call happens, i need to take that report and run it through the filters. here is the code i have.

class Filters(object):

    def __init__ (self, report, location):
        self.report = report
        self.location = location

    def get_location(self):
        return self.location

    def run(self):
        cursor = con.cursor()
        filters = cursor.execute(filterqry).fetchall()
        for i in filters:
            f = ReportFilters.fd.get(i[0])
            f.run()
        cursor.close()


class Filter1(Filters):

    def __init__(self):
    self.f1 = None
   ''' here is where i tried super() and Filters.__init__.() etc....  but couldn't make it work'''

    def run(self):
    '''Here is where i want to run the filters but as of now i am trying to print out the 
     location and the report to see if it gets the variables.'''

    print(Filters.get_location())  

class ReportFilters(Filters):

    fd = {
    'filter_1': Filter1(),
    'filter_2': Filter2(),
    'filter_3': Filter3()
    }

My errors come from the dictionary call, as when i tried to call it as it is asking for the report and location variables.

Hope this is clear enough for you to help out with, as always it is duly appreciated.

DamnGroundHog

The call to its parent class should be defined inside the init function and you should pass the arguments 'self', 'report' and 'location' into init () and Filters. init () call to parent class so that it can find those variables.

If the error is in the Filters1 class object, when you try to use run method and you do not see a location or a report variable passed in from parent class, that is because you haven't defined them when you instantiated those object in ReportFilters.fd

It should be:

class ReportFilters(Filters):
    fd = {
        'filter_1': Filter1(report1, location1),
        'filter_2': Filter2(report2, location2),
        'filter_3': Filter3(report3, location3)
    }


class Filter1(Filters):
    def __init__(self, report, location):
        Filters.__init__(self, report, location)
        self.f1 = None

    def run(self):
        print(self.get_location())

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