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

Copycating static variables (file scope) behavior

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

我在该模块中有一个功能:

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

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

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

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

有什么不太复杂的方法可以实现吗?

听起来数据库就可以了。就 import sqlite3.

正在创建 table(将其保存在当前目录中作为 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.