python - 如何在 Python 类中创建唯一且增量的 ID
问题描述
我有以下 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)
每次我在主中调用该类时,我都希望有一个增量唯一的对象类 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
推荐阅读
- swift - 为什么使用 SwiftUI 时选择器绑定不更新?
- javascript - UnhandledPromiseRejectionWarning如何处理?
- reactjs - 与 Gatsby 反应钩子。onClick 仅在第二次单击时更改 setState
- python - Python中嵌套循环的时间复杂度
- javascript - 如何使用我的反应组件中的请求 api 将字符串传递给变量?
- amazon-web-services - 嵌入 quicksight URL 时访问被拒绝
- cobol - COBOL 程序不会在我的报告中输出详细信息行
- php - 不支持的操作数类型 codeigniter 分页
- javascript - 向矢量(2D)平滑旋转线
- android-studio - 如何从 LaunchActivity 启动 MainActivity