简体   繁体   中英

How to create a unique and incremental ID in a Python Class

I have the following python classes:

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)

I would like to have an incremental unique ID of Objects class in each time I call the class in the main. This ID is got to be generated automatically while creating the class instance.

I have thought to use the function id() but it's only when creation of the object.

a = Objects(1, 2, 3, 4, 5, 6)
b = Objects(1, 2, 3, 4, 5, 6)
print (id(a),id(b)) #(2400452, 24982704)

Use the following:

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)

Running program:

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

You can do so without any extra package. This is called Class Attribute:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM