I need to make class, for which each instantiated object will have unique id (simply incremented counter). For now, all 3 objects(b, b1, b2) shares one A.__COUNTER variable.
class A(type):
__COUNTER = 0
def __call__(cls, *args, **kwargs):
setattr(cls, "id", A.__COUNTER)
A.__COUNTER += 1
return type.__call__(cls, *args, **kwargs)
class B():
__metaclass__ = A
def __init__(self):
self.id
b = B()
b1 = B()
b2 = B()
print(b.id, b1.id, b2.id) -> (2, 2, 2)
Seems like I am digging in wrong direction
P.S. SOLVED
Sorry, guys, I did not mentioned that there can be couple classes which should share same id sequence. There are bunch of solutions, here how I solved it
class A(type):
__COUNTER = 0
def __call__(cls, *args, **kwargs):
obj = type.__call__(cls, *args, **kwargs)
obj.setId(A.__COUNTER)
A.__COUNTER += 1
return obj
class B():
__metaclass__ = A
def setId(self, id):
self.id = id
class C():
__metaclass__ = A
def setId(self, id):
self.id = id
b = B()
b1 = B()
b2 = B()
c = C()
b3 = B()
print(b.id, b1.id, b2.id, c.id, b3.id) -> (0, 1, 2, 3, 4)