2016-01-25 45 views
0

我想创建一组类,每个类都有自己的唯一名称。类似这样的:具有预定义唯一标识的Python类实例

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?
类方法VS静态方法:
Meaning of @classmethod and @staticmethod for beginner?
What is the difference between @staticmethod and @classmethod in Python?

+0

你的用例是什么?对于'create'来说,使用给定的ID而不是'None'来返回一个已存在的对象似乎更自然一些。 – chepner

+0

无论你如何实现它们,多重器件都是糟糕的设计。你真的想做什么? – Kevin

+0

@chepner:我试着添加更多信息使其更加清晰。 – InvaderZim

回答

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 
相关问题