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

Categories

0 votes
1.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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...