[英]Importing variables from another python file
我正在尝试将一个 python 文件中定义的变量导入另一个文件,两者都在同一目录中。 下面是示例:
# 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()
我使用from filename1 import *
in filename2 但这些值仍然未定义并且在数据库中它存储了 NULL 个值。 关于如何将这些导入 filename2 文件的任何建议。
PS:filename1和filename2是两个不同的文件
好问题!
这里的主要问题是您在质子 class 中定义的变量是质子 object 的“实例变量”(又名字段或数据成员)。另一种思考方式是它们“属于”某个质子实例。
如果不先创建 object,我想,它们不存在!
在下面的示例中,我们首先初始化一个 Proton object,然后访问它的一个实例变量。
my_proton = Proton() # Creating a Proton object
my_proton.a_tags # Accessing the a_tags attribute
下面,我编辑了您的代码,以便您可以访问 Proton object 的实例变量。在下面的示例中,我刚刚创建了测试标签来展示您如何访问它们。
# filename1: "proton.py"
class Proton:
def __init__(self):
self.a_tags = []
self.cases = []
self.links = []
def test(self):
self.a_tags = ['test a_tags']
self.cases = ['test cases']
self.links = ['test links']
# filename2: "database.py"
import sqlite3
from proton import Proton # from the file named "proton", import the Proton class
class Database:
my_proton = Proton() # create a Proton object
print(my_proton.a_tags) # access the a_tags object from the Proton object and print
假设你已经导入了质子,如果你希望它以最小的变化工作:
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
正在调用不存在的数据库实例的cases
变量 -> None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.