Reputation: 65
So I am supposed to create a class that has A unique ID for each object (starts at 0). It should also automatically assign it a unique ID every time a new object is created. Hints (The constructor of the class should automatically assign the ID of the Geometry object. The data type of the ID is an integer and starts at 0) My output is supposed to resemble
>>>geo1 = Geometry()
>>>geo1.id
0
>>>geo2 = Geometry()
>>>geo2.id
1
My issue is id seems to be a built in function that generates a random number. But my instructions say the number is supposed to start a 0. Is there anyway to make that happen?
My code
class Geometry (object):
def __init__(geo, id):
geo.id = geo1
geo1 = Geometry(0,1)
print geo1
Upvotes: 0
Views: 135
Reputation: 152607
Just to present an alternative using __new__
and the fact that instance variables and class variables are not the same:
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
Upvotes: 0
Reputation: 46849
Geometry
could have its own 'static' instance counter:
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
every time you call __init__
the counter gets increased by one.
as far as i know the built-in id
function can not be overridden.
Upvotes: 1
Reputation: 405
Keep the next id in a class attribute:
class Geometry(object):
next_id = 0
def __init__(self):
self.id = Geometry.next_id
Geometry.next_id += 1
The counter Geometry.next_id
is saved in the class, not the instance, so it will be incremented on each instance generation:
>>> geo1 = Geometry()
>>> geo1.id
0
>>> geo2 = Geometry()
>>> geo2.id
1
Upvotes: 1