我想为我创建的每个对象创建一个唯一的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)
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)
小智 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.
您是否了解python 中的id函数,并且可以使用它代替您的反思想吗?
class C(): pass
x = C()
y = C()
print(id(x), id(y)) #(4400352, 16982704)
Run Code Online (Sandbox Code Playgroud)
尝试使用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)