[英]unpacking class variables as a list
假設我有一個“數組”
self.memory = [None] * 10000
現在讓我們說我有一個像這樣的課程:
class Process:
def __init__(self, process_id, state, priority):
self.process_id = process_id
self.state = state
self.priority = priority
def operation_that_adds_class_variables(self):
if self.priority > 5:
self.urgency = 'HIGH'
else:
self.urgency = 'LOW'
我要對memory
做一些事情,現在它具有一些值了。 我找到了第一次出現的None
並且想要在其中放置一個Process
。 但是,我希望該類的實例解壓縮其初始化的self
變量
def CreateProcess(process_id, state, priority):
print 'memory before create process'
print self.memory
index = self.memory.index(None)
p = Process(process_id, state, priority)
ready_queue.append(p)
self.memory[index] = #unpack p, with offsets in memory
print 'memory after create process'
print self.memory
本質上,這就是我的期望。
Memory before create process:
[1, 2, 3, 4, None, None, None, None ...]
Memory after create process
[1, 2, 3, 4, PROCESS_1, states['pending'], 3, 'HIGH URGENCY', ...]
這容易實現嗎?
使用切片分配:
self.memory[index:index + 4] = p.process_id, p.state, p.priority, p.urgency
注意這可以擴展self.memory
; 您可能要先進行邊界檢查:
if index <= len(self.memory) - 4:
演示:
>>> memory = [1, 2, 3, 4, None, None, None, None]
>>> index = memory.index(None)
>>> memory[index:index + 4] = 'foo', 'bar', 'spam', 'eggs'
>>> memory
[1, 2, 3, 4, 'foo', 'bar', 'spam', 'eggs']
為了支持可變數量的屬性,可以擴展Process
類以跟蹤需要包括哪些屬性:
class Process:
urgency = None
def __init__(self, process_id, state, priority):
self.process_id = process_id
self.state = state
self.priority = priority
def operation_that_adds_class_variables(self):
if self.priority > 5:
self.urgency = 'HIGH'
else:
self.urgency = 'LOW'
@property
def memory_values(self):
res = (self.process_id, self.state, self.priority)
if self.urgency is not None:
return res + (self.urgency,)
return res
然后將其結果存儲在您的“內存”中:
proc_memory = p.memory_values
if index <= len(self.memory) - len(proc_memory):
self.memory[index:index + len(proc_memory)] = proc_memory
您不能隨意列出屬性,因為擁有屬性的實例__dict__
對象是一個字典。 它沒有命令。 您必須自己指定一個訂單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.