,所以我应该创建一个具有每个对象具有唯一ID的类(从0开始)。每当创建新对象时,它还应该自动为其分配一个唯一的ID。提示(类的构造函数应自动分配几何对象的ID。我的输出应该类似于
>>>geo1 = Geometry()
>>>geo1.id
0
>>>geo2 = Geometry()
>>>geo2.id
1
我的问题是ID似乎是生成随机数的内置函数。但是我的说明说这个数字应该开始一个0。
我的代码
class Geometry (object):
def __init__(geo, id):
geo.id = geo1
geo1 = Geometry(0,1)
print geo1
在类属性中保留下一个ID:
class Geometry(object):
next_id = 0
def __init__(self):
self.id = Geometry.next_id
Geometry.next_id += 1
计数器Geometry.next_id
保存在类中,而不是实例中,因此每个实例生成都会增加:
>>> geo1 = Geometry()
>>> geo1.id
0
>>> geo2 = Geometry()
>>> geo2.id
1
Geometry
可以具有自己的'静态'实例计数器:
class Geometry (object):
current_id = 0
def __init__(self):
self.id = Geometry.current_id
Geometry.current_id += 1
geo0 = Geometry()
print(geo0.id) # -> 0
geo1 = Geometry()
print(geo1.id) # -> 1
每次您致电__init__
时,计数器都会增加一个。
据我所知,内置的id
功能不能被覆盖。
只是为了使用 __new__
提出替代方案,事实是实例变量和类变量不相同:
class Geometry(object):
# create a class variable
id = 0
def __new__(cls, *args, **kwargs):
# Create a new object
obj = object.__new__(cls, *args, **kwargs)
# assign the next id as instance variable
obj.id = cls.id
# increment the class variable
cls.id += 1
# return the object
return obj
def __init__(self):
pass
>>> geo1 = Geometry()
>>> print(geo1.id)
0
>>> geo2 = Geometry()
>>> print(geo2.id)
1
>>> geo3 = Geometry()
>>> print(geo3.id)
2