简体   繁体   English

具有预定义唯一ID的Python类实例

[英]Python class instances with predefined unique id

I want to create a set of classes, each with their own unique name. 我想创建一组类,每个类都有自己的唯一名称。 Something like this: 像这样:

    class B(object):
        # existing_ids = []
        existing_ids = set()

        @staticmethod
        def create(my_id):
            if my_id not in B.existing_ids:
                # B.existing_ids.append(my_id)
                B.existing_ids.add(my_id)
                # return B(my_id)
            else:
                return None

            # Added block
            if style == 'Ba':
                return Ba(my_id, style)
            else:
                return None

        def __init__(self, my_id):
            self.my_id = my_id
            self.style = style  # Added

        # Added function
        def save(self):
            with open('{}.pkl'.format(self.my_id), 'ab') as f:
                pickle.dump(self.data, f, pickle.HIGHEST_PROTOCOL)

        # Added function
        def foo(self):
            self.data = 'B_data'

    # Added class
    class Ba(B):
        def __init__(self, my_id, style):
            super().__init__(my_id, style)

        def foo(self):
            self.data = 'Ba_data'

    # Edited part
    a = B.create('a', 'Ba')
    b = B.create('b', 'Ba')
    c = B.create('b', 'Ba')

    print(B.existing_ids, a.existing_ids, b.existing_ids, c)
    # {'a', 'b'} {'a', 'b'} {'a', 'b'} None

Is this a good idea? 这是一个好主意吗? Are there better or other ways to do this? 有更好的方法或其他方法吗?

EDIT: I understand that my example was a bit confusing. 编辑:我知道我的例子有点混乱。 I've now updated it a bit to better show what I am trying to achieve. 我现在对其进行了一些更新,以更好地展示我要实现的目标。 For my problem I will also have class Bb(B), class Bc(B), etc. 对于我的问题,我还将拥有Bb(B)类,Bc(B)等类。

This thread seems like the most related: 该线程似乎是最相关的:
Static class variables in Python Python中的静态类变量

The basics: Python - Classes and OOP Basics 基础知识: Python-类和OOP基础知识
Metaclasses could be relevant, but it also goes a bit over my head: 元类可能是相关的,但也让我有些头疼:
What is a metaclass in Python? Python中的元类是什么?
Classmethod vs static method: 类方法与静态方法:
Meaning of @classmethod and @staticmethod for beginner? @classmethod和@staticmethod对初学者的意义?
What is the difference between @staticmethod and @classmethod in Python? Python中的@staticmethod和@classmethod有什么区别?

At the very least, B.create becomes simpler if you use a set instead of a list to store allocated IDs. 至少,如果使用集合而不是列表来存储分配的ID,则B.create变得更简单。

class B(object):
    existing_ids = set()

    @staticmethod
    def create(my_id):
        if my_id not in existing_ids:
            existing_ids.add(my_id)
            return B(my_id)

    def __init__(self, my_id):
        self.my_id = my_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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