为所有节点都提供唯一的ID? [英] Giving unique IDs to all nodes?

查看:36
本文介绍了为所有节点都提供唯一的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python创建一个类,该类将许多节点和边缘联系在一起.我还有其他操作,可以将两个单独的对象合并到相同类型的单个对象中,依此类推.

I am making a class in Python that relates a lot of nodes and edges together. I also have other operations that can take two separate objects and merge them into a single object of the same type, and so on.

但是,我需要一种为每个节点赋予唯一ID以便于查找的方法.是否有适当的方法"来执行此操作,还是仅在每次向任何对象添加更多节点时都必须保留一个递增并传递到类方法中的外部ID变量?

However, I need a way to give every node a unique ID for easy lookup. Is there a "proper way" to do this, or do I just have to keep an external ID variable that I increment and pass into my class methods every time I add more nodes to any object?

我还考虑过在创建时为每个节点生成一个随机字符串,但是仍然存在发生冲突错误的风险(即使该概率接近零,它仍然存在并且看起来像是设计缺陷,即使不是经过漫长的过度设计也是如此)无论如何)

I also considered generating a random string for each node upon creation, but there is still a risk of collision error (even if this probability is near-zero, it still exists and seems like a design flaw, if not a longwinded overengineered way of going about it anyway).

推荐答案

您可以保留一个类变量并将其用于顺序ID:

You could keep a class variable and use it for ordinal ids:

class Node(object):
    _id = 0

    def __init__(self):
        self._id = Node._id
        Node._id += 1

它还有一个好处,您的类将能够知道总共创建了多少个对象.

It also has the benefit that your class will be able to know how many objects were altogether created.

这也比随机ID便宜.

这篇关于为所有节点都提供唯一的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆