如何在Python类中创建增量ID

mea*_*ade 23 python class

我想为我创建的每个对象创建一个唯一的ID - 这是类:

class resource_cl :
    def __init__(self, Name, Position, Type, Active):
        self.Name = Name
        self.Position = Position
        self.Type = Type
        self.Active = Active
Run Code Online (Sandbox Code Playgroud)

我希望有一个self.ID,每次我创建一个新的类引用时自动递增,例如:

resources = []
resources.append(resource_cl('Sam Sneed', 'Programmer', 'full time', True))
Run Code Online (Sandbox Code Playgroud)

我知道我可以参考resource_cl,但我不确定如何从那里开始......

Alg*_*ias 52

简洁优雅:

import itertools

class resource_cl():
    newid = itertools.count().next
    def __init__(self):
        self.id = resource_cl.newid()
        ...
Run Code Online (Sandbox Code Playgroud)

  • Python3已删除`.next()`,因此您可以尝试以下方法:/sf/answers/3802279141/ (3认同)
  • +1:这是在所有当前答案中唯一可靠且线程安全的方法。id可能会返回非唯一值,而仅仅在__init__内部增加类变量可能会导致竞争条件。我还喜欢将引用存储到`count()。next`而不是直接存储`count()`的结果的想法。 (2认同)
  • 正如 @foxyblue 所说,python3 删除了 `.next()` 并将其替换为 `next` 内置函数。然而,内置的“next”仅引用“count”返回的迭代器的“__next__”方法,因此您只需将“.next”替换为“.__next__”即可。 (2认同)

S.L*_*ott 19

首先,使用类的大写名称.属性的小写名称.

class Resource( object ):
    class_counter= 0
    def __init__(self, name, position, type, active):
        self.name = name
        self.position = position
        self.type = type
        self.active = active
        self.id= Resource.class_counter
        Resource.class_counter += 1
Run Code Online (Sandbox Code Playgroud)

  • 在__init__中,class_counter引用是类的属性.它应该如下所示:Resource.class_counter + = 1 (3认同)
  • 如果需要支持类继承,可能需要使用`self .__ class __.class_counter + = 1`而不是`Resource.class_counter + = 1` (3认同)
  • self将在访问该值时工作.所以:self.id = self.class_counter将根据需要表现,因为属性解析将回退到class属性.这不是设置属性的情况,因为值集将在实例的范围内而不是基础类. (2认同)

小智 15

使用来自itertools的 count 非常适合:

>>> import itertools
>>> counter = itertools.count()
>>> a = next(counter)
>>> print a
0
>>> print next(counter)
1
>>> print next(counter)
2
>>> class A(object):
...   id_generator = itertools.count(100) # first generated is 100
...   def __init__(self):
...     self.id = next(self.id_generator)
>>> objs = [A(), A()]
>>> print objs[0].id, objs[1].id
100 101
>>> print next(counter) # each instance is independent
3
Run Code Online (Sandbox Code Playgroud)

如果您以后需要更改值的生成方式,则只需更改其定义即可使用相同的界面id_generator.


lli*_*lib 8

您是否了解python 中的id函数,并且可以使用它代替您的反思想吗?

class C(): pass

x = C()
y = C()
print(id(x), id(y))    #(4400352, 16982704)
Run Code Online (Sandbox Code Playgroud)

  • 请记住,在程序的一次执行中,不能保证由id()返回的值是唯一的(它们可以在收集对象时被重用)。也不能保证它们遵循任何特定的模式(您最初确实要求自动递增)。 (13认同)
  • 如果要为存档或网络io腌制对象,则使用内置的id()是不明智的。另一端的计算机可能已经有一个具有该id()的对象。 (2认同)

fox*_*lue 8

尝试使用python 3中投票最高的答案,由于.next()已被删除,您会遇到错误。

相反,您可以执行以下操作:

import itertools

class BarFoo:

    id_iter = itertools.count()

    def __init__(self):
        # Either:
        self.id = next(BarFoo.id_iter)

        # Or
        self.id = next(self.id_iter)
        ...
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案。它就像一个魅力! (5认同)