Reputation: 481
I have the following python classes:
class Coordinates:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class Properties:
def __init__(self, w, h, d):
self.w = w
self.h = h
self.d = d
class Objects(Properties, Coordinates):
def __init__(self, x, y, z, w, h, d):
Coordinates.__init__(self, x, y, z)
Properties.__init__(self, w, h, d)
I would like to have an incremental unique ID of Objects class in each time I call the class in the main. This ID is got to be generated automatically while creating the class instance.
I have thought to use the function id()
but it's only when creation of the object.
a = Objects(1, 2, 3, 4, 5, 6)
b = Objects(1, 2, 3, 4, 5, 6)
print (id(a),id(b)) #(2400452, 24982704)
Upvotes: 2
Views: 3128
Reputation: 150735
You can do so without any extra package. This is called Class Attribute:
class MyClass(object):
counter = 0
def __init__(self):
# other commands here
# update id
self.id = MyClass.counter
MyClass.counter += 1
a,b = MyClass(), MyClass()
print(a.id, b.id)
# 0 1
Upvotes: 1
Reputation: 69755
Use the following:
import itertools
class Objects(Properties, Coordinates):
id_iter = itertools.count()
def __init__(self, x, y, z, w, h, d):
Coordinates.__init__(self, x, y, z)
Properties.__init__(self, w, h, d)
self.id = next(Objects.id_iter)
Running program:
>> a = Objects(1, 2, 3, 4, 5, 6)
>>> b = Objects(1, 2, 3, 4, 5, 6)
>>> print (a.id, b.id) # the id will depend upon the number of objects already created
0 1
Upvotes: 3