Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

Importing variables from another python file

I am trying to import variables defined in one python file in another file , both are in same directory. Below is the sample:

# filename1

class Proton:

 def test(self):

   self.a_tags = soup_file.find_all('a')
   self.cases = [str(each.get_text()) for each in self.a_tags]
   self.links = [(link.get('href')) for link in soup_file.find_all('a')]

# I want to import the above values in the below file

# filename2

import sqlite3

class Database:

    def __init__(self):

        self.create_connection()
        self.create_table()

    def create_connection(self):
        self.conn = sqlite3.connect('gopel.db')
        self.curr = self.conn.cursor()

    def create_table(self):

        self.curr.execute('''CREATE TABLE testfall(cases TEXT, links TEXT)''')

    def testfall_db(self):

        self.curr.execute('''INSERT INTO testfall VALUES(?,?)''',(self.cases,self.links,))
        self.curr.execute('''SELECT cases FROM testfall WHERE cases=?''', [self.cases])
        self.conn.commit()

I used from filename1 import * in filename2 but the values are still undefined and in the database its storing NULL values. Any suggestion on how to import these to the filename2 file.

PS: filename1 and filename2 are two different files


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming you've imported Proton, if you want it to work with minimal changes:

def testfall_db(self):

    p = Proton() # need to create the instance first
    p.test()     # call the test method to initialize those values

    # access those values from the `p` instance of Proton created above
    self.curr.execute('''INSERT INTO testfall VALUES(?,?)''',(p.cases,p.links,))
    self.curr.execute('''SELECT cases FROM testfall WHERE cases=?''', [p.cases])
    self.conn.commit()

self.cases in your code for example, is calling the cases variable of the Database instance which does not exist -> None.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...