繁体   English   中英

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

[英]Python class instances with predefined unique id

我想创建一组类,每个类都有自己的唯一名称。 像这样:

    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

这是一个好主意吗? 有更好的方法或其他方法吗?

编辑:我知道我的例子有点混乱。 我现在对其进行了一些更新,以更好地展示我要实现的目标。 对于我的问题,我还将拥有Bb(B)类,Bc(B)等类。

该线程似乎是最相关的:
Python中的静态类变量

基础知识: Python-类和OOP基础知识
元类可能是相关的,但也让我有些头疼:
Python中的元类是什么?
类方法与静态方法:
@classmethod和@staticmethod对初学者的意义?
Python中的@staticmethod和@classmethod有什么区别?

至少,如果使用集合而不是列表来存储分配的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