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

2024-04-20 13:23:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

我无法将其保存到文件中,不仅访问速度会慢很多,而且我需要的静态数据的大小非常大,每次都必须加载。你知道吗

我想让我的模块在一个永久循环中运行(好吧,直到它被告知另一个),并监听进程间通信(这意味着我不会导入它,只是让它接收来自“导入”程序的请求并发送必要的响应)。对我来说,这可能就足够了——因为该模块所做的只是生成一个随机序列号,并确保它不会出现在used_serials(为了实现这一点,它应该是静态的)列表中(我不想使用文件的原因是因为我在很短的时间内生成了大量的序列号)——但是我想知道有一个不那么复杂的解决方案。你知道吗

有没有什么不太复杂的方法来实现这一点?你知道吗


Tags: 模块文件对象程序功能mydef静态
1条回答
网友
1楼 · 发布于 2024-04-20 13:23:58

听起来像是一个数据库。只是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。你知道吗

相关问题 更多 >