2 回答

TA贡献1789条经验 获得超8个赞
这里最简单的方法是一个类变量,它存储下一个要使用的值,在使用后递增:
class BankAccount:
_nextnum = 1
def __init__(self, balance):
self.account_number = "B" + str(self._nextnum)
type(self)._nextnum += 1 # Must set it on the class, or you only make a shadowing instance attribute
self.balance = balance
但是,如果没有锁定,这不是线程安全的,因此如果您想要线程安全,itertools.count可以以线程安全(至少在 CPython 上)的方式完成相同的工作:
import itertools
class BankAccount:
_numgenerator = itertools.count(1)
def __init__(self, balance):
self.account_number = "B" + str(next(self._numgenerator))
self.balance = balance
由于itertools.count的工作是在保持 GIL的 C 层完成的,因此它以原子方式运行,既返回下一个数字又将计数作为单个原子操作移动。
添加回答
举报