簡體   English   中英

如何在 Python Class 中創建唯一且增量的 ID

[英]How to create a unique and incremental ID in a Python Class

我有以下 python 類:

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)

每次我主要調用 class 時,我都希望有一個增量的唯一 ID 對象 class。 此 ID 必須在創建 class 實例時自動生成。

我曾想過使用 function id()但僅在創建 object 時使用。

a = Objects(1, 2, 3, 4, 5, 6)
b = Objects(1, 2, 3, 4, 5, 6)
print (id(a),id(b)) #(2400452, 24982704)

使用以下內容:

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)

運行程序:

>> 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

您可以在沒有任何額外的 package 的情況下這樣做。 這稱為 Class 屬性:

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

暫無
暫無

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

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