gpt4 book ai didi

python - 复制静态变量(文件范围)行为

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:47 25 4
gpt4 key购买 nike

我所说的静态是指对象(变量)不会改变。假设我有一个名为 my_static_vars 的 python 模块,它包含 a,其起始值为 10(整数)。

我在该模块中有一个函数:

def prntandinc(): #print and increase
print a
a += 1

当我从另一个程序导入模块时,我希望它输出 11。但如果没有任何特殊限制,我不会问这个问题。

不能保存到文件中,不仅访问会慢很多,而且我要静态化的数据量很大,每次都要加载。

我想过让我的模块在一个永久循环中运行(好吧,除非另有说明)并监听进程间通信(这意味着我不会导入它,只是让它接收来自“导入”程序的请求并且发送必要的回复)。现在,在我的例子中,这可能就足够了——因为该模块所做的只是生成一个随机序列号,并确保它不会出现在 used_serials 中(这应该是静态的,这样才有可能) 列表(我不想使用文件的原因是因为我在相当短的时间内生成了大量序列号)- 但我想知道是否有更简单的解决方案。

有什么不太复杂的方法可以做到这一点吗?

最佳答案

听起来像数据库就可以了。只需import sqlite3

创建表(将其作为serials.db保存在当前目录中):

import sqlite3
conn = sqlite3.connect('serials.db') #Will create a new table as it doesn't exist right now
cur = conn.cursor() #We will use this to execute commands
cur.execute('''CREATE TABLE serials_tb (serial text)''') #for more than one column add a comma, as in a tuple, and write '[COL_NAME] [COL_TYPE]' without the apostrophes. You might want (as I suppose you only want a serial to be used once) to define it as a primary key
conn.commit()
conn.close()

添加序列号:

import sqlite3
conn = sqlite3.connect('serials.db') #Will connect to the existing database
cur = conn.cursor()
data = ('MY_SERIAL',) #a tuple
cur.execute('''INSERT INTO serials_tb VALUES (?)''', data)
conn.commit()
conn.close()

选择一个连续剧(看它是否已经存在):

import sqlite3
conn = sqlite3.connect('serials.db') #Will connect to the existing database
cur = conn.cursor()
data = ('MY_SERIAL',)
qry = cur.execute('''SELECT * FROM serials_tb WHERE serial=?''', data)
#You can iterate over it and get a tuple of each row ('for row in qry:')
#But to check if a col exists, in your case, you can do so:
if len(qry.fetchall()) != 0:
#The serial is used
else:
#The serial isn't used

注意:显然,您不需要每次都导入 sqlite3(仅在每个文件中,而不是每次执行命令时,也不需要每次都连接或关闭连接执行命令。在需要时提交更改,在开始时连接并在结束时关闭连接。更多信息,您可以阅读 here .

关于python - 复制静态变量(文件范围)行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34453164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com