将类变量解压缩为列表

时间:2014-03-08 18:04:00

标签: python python-2.7

假设我有一个“数组”

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', ...]

这是否可以轻松实现?

1 个答案:

答案 0 :(得分:1)

使用切片分配:

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__对象持有属性是字典;它没有订单。您必须自己指定订单。