簡體   English   中英

為Python中的每個對象設置唯一的ID

[英]Set unique id for each object in Python

我需要創建類,對於該類,每個實例化的對象都將具有唯一的ID(僅增加計數器)。 現在,所有三個對象(b,b1,b2)共享一個A .__ COUNTER變量。

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)

好像我挖錯了方向

PS 解決了

抱歉,伙計們,我沒有提到可以有幾個應該共享相同ID序列的類。 有很多解決方案,這是我如何解決的

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)

好吧,Python中的所有對象已經具有唯一的ID

>>> id("a string")
140588614961168

但是,如果您想要一個單獨的計數器,則可以使用您使用的方法。 但是,有關為什么您希望這樣做的更多信息可能會有所幫助。

您可以只使用類變量:

class B ():
    __lastId = 1

    def __init__ (self):
        self.id = B.__lastId
        B.__lastId += 1
>>> [B().id for _ in range(10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

什么是元類中所述? ,元類是類的類,而您只想修改單個類型的實際實例化的對象。 因此,這里無需深入了解元類的復雜性級別。

一個好的解決方案取決於用例。 我提供了一種非常通用的。

IDAssigner是將ID粘貼到創建的所有內容上的工廠。 為新的ID池創建IDAssigner實例。 您調用IDAssigner的實例,該實例將類實例化為第一個參數,后跟該類的__init__方法的參數。

from itertools import count


class IDAssigner(object):
    def __init__(self):
        self._next_id = count()

    def __call__(self, klass, *args, **kwargs):
        obj = klass(*args, **kwargs)
        setattr(obj, 'id', next(self._next_id))
        return obj


class Foo(object):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return self.value


create = IDAssigner()
foo_1 = create(Foo, 'Hello')
foo_2 = create(Foo, 'World')
print(foo_1, foo_1.id)
print(foo_2, foo_2.id)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM