如何在 Python 类中创建唯一且增量的 ID

2024-01-30

我有以下 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)

我希望每次在 main 中调用该类时都有一个增量的对象类唯一 ID。该 ID 在创建类实例时自动生成。

我想过使用该功能id()但只有在创建对象时才有效。

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Python 类中创建唯一且增量的 ID 的相关文章

随机推荐