简体   繁体   English

Python 3:将变量从一个CLASS传递到另一个

[英]Python 3: Pass variable from one CLASS to another

I have a beginner problem here. 我在这里有一个初学者的问题。 I have a parent Class that contains a call to SQLite DB and to ConfigParser ini file and I want my child Class to access all those pieces of information. 我有一个父类,其中包含对SQLite DB和ConfigParser ini文件的调用,我希望我的子类访问所有这些信息。

Below is my code and what I've tried so far with no success. 以下是我的代码以及到目前为止我没有尝试过的尝试。 I understand instantiation but only with minimal examples like employees/salaries lol. 我了解实例化,但仅使用最少的示例,例如雇员/薪水大声笑。

My code works if I copy all the calls to DB and config files into the child Class and it's not how it should be done, I know. 如果我将对数据库和配置文件的所有调用复制到子类中,则我的代码有效,我知道这不是应该完成的工作。 Could you please help me? 请你帮助我好吗?

class SimpleGrid(gridlib.Grid): ##, mixins.GridAutoEditMixin):
    def __init__(self, parent, log):
        gridlib.Grid.__init__(self, parent, -1)

        self.wxFont = "9, wx.FONTFAMILY_DEFAULT, wx.NORMAL, wx.NORMAL"

        path =os.path.dirname(os.path.realpath(__file__))
        configFile = os.path.join(path , "config.ini")

        dbfile = os.path.join(path , "report.db")
        self.db_conn = sqlite3.connect(dbfile)
        self.theCursor =  self.db_conn.cursor()

        config = configparser.ConfigParser()
        config.read(configFile)


        if config.get('Network', 'taboola') == "true" and config.get('Network', 'outbrain') == "true":
            network = ""
        elif config.get('Network', 'taboola') == "true" and config.get('Network', 'outbrain') == "false":
            network = " and CAMPAIGN LIKE '%TB%'"
        elif config.get('Network', 'outbrain') == "true" and config.get('Network', 'taboola') == "false":
            network = " and CAMPAIGN LIKE '%OB%'"
        else:
            network = ""

        if config.get('Sort', 'value') == "Impr.":
            sort = "IMPR" 
        elif config.get('Sort', 'value') == "Clicks":
            sort = "CLICKS"
        elif config.get('Sort', 'value') == "CTR":
            sort = "CTR"  
        elif config.get('Sort', 'value') == "CPC":
            sort = "CPC"  
        elif config.get('Sort', 'value') == "eCPC":
            sort = "eCPC"
        elif config.get('Sort', 'value') == "Spent":
            sort = "SPENT"
        elif config.get('Sort', 'value') == "Revenue":
            sort = "GA_REV" 
        elif config.get('Sort', 'value') == "GA Impr.":
            sort = "GA_IMPR"  
        elif config.get('Sort', 'value') == "GA Clicks":
            sort = "GA_CLICKS"
        elif config.get('Sort', 'value') == "GA CTR":
            sort = "GA_CTR"
        elif config.get('Sort', 'value') == "Rev. /1000":
            sort = "GA_RPM"
        else:
            sort = "SPENT"

        #['Impr.', 'Clicks', 'CTR', 'CPC', 'eCPC', 'Spent', 'Revenue', 'GA Impr.', 'GA Clicks', 'GA CTR', 'Rev. /1000'] 

        if config.get('Filter', 'column') == "Campaign":
            column = "CAMPAIGN"
        elif config.get('Filter', 'column') == "Impr.":
            column = "IMPR"
        elif config.get('Filter', 'column') == "Clicks":
            column = "CLICKS"
        elif config.get('Filter', 'column') == "CTR":
            column = "CTR" 
        elif config.get('Filter', 'column') == "CPC":
            column = "CPC"  
        elif config.get('Filter', 'column') == "eCPC":
            column = "eCPC"    
        elif config.get('Filter', 'column') == "Spent":
            column = "SPENT"
        elif config.get('Filter', 'column') == "Revenue":
            column = "GA_REV" 
        elif config.get('Filter', 'column') == "GA Impr.":
            column = "GA_IMPR"
        elif config.get('Filter', 'column') == "GA Clicks":
            column = "GA_CLICKS"
        elif config.get('Filter', 'column') == "GA CTR":
            column = "GA_CTR"        
        elif config.get('Filter', 'column') == "Rev. /1000":
            column = "GA_RPM"
        else:
            column = ""

        if config.get('Filter', 'operator') == "Contains":
            query = "and " + column + " LIKE '%" + config.get('Filter', 'string') + "%'"
        elif config.get('Filter', 'operator') == "Doesn't Contain":
            query = "and " + column + " NOT LIKE '%" + config.get('Filter', 'string') + "%'"


        if config.get('Filter', 'operator') == "<":
            query = "and " + column + " < " + config.get('Filter', 'string')
        elif config.get('Filter', 'operator') == ">":
            query = "and " + column + " > " + config.get('Filter', 'string')

        #To instantiate
        queryFiltre = "SELECT * FROM Report WHERE  GA_RPM > 0 " + query + network + "  and STATUS = '1' ORDER BY " + sort + " DESC"
        print(queryFiltre) 

        rows = self.db_conn.execute(queryFiltre)
        rowsCount = len(rows.fetchall())

class TestFrame(wx.Frame):
    def __init__(self, parent, log):
        wx.Frame.__init__(self, parent, 0, "V1.0", size=(1400,800))
        self.grid = SimpleGrid(self, log)

What I've done so far: 到目前为止,我所做的是:

class SimpleGrid(gridlib.Grid): ##, mixins.GridAutoEditMixin):
    def __init__(self, parent, log):
        gridlib.Grid.__init__(self, parent, -1)


        self.wxFont = "9, wx.FONTFAMILY_DEFAULT, wx.NORMAL, wx.NORMAL"
        self.queryFiltre = ""

        def setQueryFiltre(queryFiltre):
            path =os.path.dirname(os.path.realpath(__file__))
            configFile = os.path.join(path , "config.ini")
            dbfile = os.path.join(path , "report.db")
            self.db_conn = sqlite3.connect(dbfile)
            self.theCursor =  self.db_conn.cursor()

            config = configparser.ConfigParser()
            config.read(configFile)

            #All the calls to DB and config file here

            return queryFiltre

        def getQueryFiltre(queryFiltre):
            queryFiltre = queryFiltre

        rows = db_conn.execute(queryFiltre)
        rowsCount = len(rows.fetchall())


class TestFrame(wx.Frame):
    def __init__(self, parent, log):
        wx.Frame.__init__(self, parent, 0, "V1.0", size=(1400,800))
        self.grid = SimpleGrid(self, log)

        self.wxFont = SimpleGrid(self.wxFont)
        self.queryFiltre = SimpleGrid.getQueryFiltre()

But here the first error I get is the db_conn is not defined and I'm sure I will still have more to handel if this one is taken car of. 但是在这里,我得到的第一个错误是未定义db_conn,而且我敢肯定,如果这辆车被盗,我还会有更多工作要做。 In fact all the variables within the def setQueryFiltre should be accessible from within both the parent and the child Classes. 实际上,可以从父类和子类中访问def setQueryFiltre中的所有变量。

Thank you, 谢谢,

EDIT: 编辑:

With oe without self. 有了oe而没有自我。 i still get the same error 我仍然遇到相同的错误 在此处输入图片说明

You declared 2 functions inside your constructor, which never get called: setQueryFiltre and getQueryFiltre . 您在构造函数中声明了两个函数,它们从未被调用: setQueryFiltregetQueryFiltre Moreover, your test calls one of them as if it was a class method. 而且,您的测试将调用其中一个,就好像它是一个类方法一样。 It's not, and it will fail becuase that declaration is only visible inside the function. 并非如此,因为声明仅在函数内部可见,因此失败。 What you probably meant to write is this: 您可能要写的是这样的:

class SimpleGrid(gridlib.Grid): ##, mixins.GridAutoEditMixin):
    def __init__(self, parent, log):
        gridlib.Grid.__init__(self, parent, -1)
        self.setQueryFiltre(None)

        self.wxFont = "9, wx.FONTFAMILY_DEFAULT, wx.NORMAL, wx.NORMAL"
        self.queryFiltre = ""

    def setQueryFiltre(self, queryFiltre):
        path = os.path.dirname(os.path.realpath(__file__))
        configFile = os.path.join(path , "config.ini")
        dbfile = os.path.join(path , "report.db")
        self.db_conn = sqlite3.connect(dbfile)
        self.theCursor =  self.db_conn.cursor()

        config = configparser.ConfigParser()
        config.read(configFile)

        #All the calls to DB and config file here
        return queryFiltre # why are you returning the argument? For chaining?

    def getQueryFiltre(self, queryFiltre):
        queryFiltre = queryFiltre

        rows = self.db_conn.execute(queryFiltre)
        rowsCount = len(rows.fetchall())
        # you probably want to return rows here?


class TestFrame(wx.Frame):
    def __init__(self, parent, log):
        wx.Frame.__init__(self, parent, 0, "V1.0", size=(1400,800))
        self.grid = SimpleGrid(self, log)

        # self.wxFont = SimpleGrid(self.wxFont) # what does this try to do?
        self.queryFiltre = self.grid.getQueryFiltre()

In Python, indentation is important. 在Python中,缩进很重要。

Note that I also moved db initialization to constructor, where it belongs. 请注意,我还将数据库初始化移动到了它所属的构造函数中。 Because otherwise, if get method gets called before set, you will still have the same crash. 因为否则,如果在设置之前调用get方法,则仍然会发生相同的崩溃。 I also made a couple other comments that you'll probably get bitten by next. 我还发表了其他几条评论,您接下来可能会被咬伤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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