Skip to main content
 首页 » 编程设计

python:为每个新对象添加数字

2025年05月04日9youxin

我想在每次创建对象时更改对象的名称,以便每次创建对象时都会添加一个累加器。在此示例中,我希望第一个 object.name 为 B1,然后第二个 object.name 为 B2,然后是 B3,依此类推。这就是我想要得到的

 class Object: 
    def __init__(self): 
         self.name = "B" + (accumulator) 

这是我尝试过的,但我并没有真正取得任何进展

class BankAccount: 
    def __init__(self, balance): 
        self.account_number = "B" + str(number = number + 1) 
        self.balance = balance 

我想不出一种方法来避免尝试将变量设置为等于加上它自身之一的问题,因为它本身尚未定义。

请您参考如下方法:

这里最简单的方法是一个类变量,它存储下一个要使用的值,在使用后递增:

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 can do the same job以线程安全(至少在 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 的工作是在 C 层用 the GIL held 完成的,它以原子方式运行,返回下一个数字并将计数作为单个原子操作移动。