如何在 Python 类中创建增量 ID [英] How do you create an incremental ID in a Python Class

查看:29
本文介绍了如何在 Python 类中创建增量 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我创建的每个对象创建一个唯一 ID - 这是类:

I would like to create a unique ID for each object I created - here's the class:

class resource_cl :
    def __init__(self, Name, Position, Type, Active):
        self.Name = Name
        self.Position = Position
        self.Type = Type
        self.Active = Active

我想要一个 self.ID,每次我创建对类的新引用时都会自动递增,例如:

I would like to have a self.ID that auto increments everytime I create a new reference to the class, such as:

resources = []
resources.append(resource_cl('Sam Sneed', 'Programmer', 'full time', True))

我知道我可以参考 resource_cl,但我不知道如何从那里开始......

I know I can reference resource_cl, but I'm not sure how to proceed from there...

推荐答案

你知道 id 函数在python中,你能用它代替你的反面想法吗?

Are you aware of the id function in python, and could you use it instead of your counter idea?

class C(): pass

x = C()
y = C()
print(id(x), id(y))    #(4400352, 16982704)

这篇关于如何在 Python 类中创建增量 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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