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

时间:2016-01-25 17:09:11

标签: python class

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

    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)等等。

这个帖子似乎最相关:
Static class variables in Python

基础知识: Python - Classes and OOP Basics
元类可能是相关的,但它也有点过头了:
What is a metaclass in Python?
Classmethod与静态方法:
Meaning of @classmethod and @staticmethod for beginner?
What is the difference between @staticmethod and @classmethod in Python?

1 个答案:

答案 0 :(得分:0)

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