[英]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.