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