2014-10-05 63 views
1

我需要迭代对象内的多个属性。每个属性都初始化为None,并且在程序过程中每个属性都会存储一个单独的对象。我需要迭代16个属性,条件是属性将按预定顺序存储对象。例如,如果属性10为空,则属性11到16也将为空,因此我不需要遍历任何空属性。我最初的结果是使用“如果”每个语句属性是这样的:Python:在条件内对预定条件进行迭代

Class Object1: 
    def __init__(self): 
     self.attribute1=None 
     self.attribute2=None 
     self.attribute3=None 
     self.attribute4=None 
     ... 

    def repeating_function(self): 
     if self.attribute1!=None: 
      self.attribute1.attribute=Callback1 
     if self.attribute2!=None: 
      self.attribute2.attribute=Callback2 
     if self.attribute3!=None: 
      self.attribute3.attribute=Callback3 
     ... 

但是,由于其中的属性存储对象,我结束了这个序列:

class Object1: 
    def __init__(self): 
     self.attribute1=None 
     self.attribute2=None 
     self.attribute3=None 
     self.attribute4=None 
     self.attribute5=None 

    def repeating_function(self): 
     if self.attribute1!=None: 
      self.attribute1.attribute=Callback1 
      if self.attribute2!=None: 
       self.attribute2.attribute=Callback2 
       if self.attribute3!=None: 
        self.attribute3.attribute=Callback3 
        ... 

基本上,我的问题是:如果第二个例子在迭代非空属性时效率更高。因为我在第二个示例中添加了条件,所以我不确定哪种方法更高效。

+2

如果用“高效”来表示速度,那么就忘了它。想想你要花多长时间来编写,阅读或维护这样的代码。想出一个方法来做一个列表或字典,并忘记微秒。 – alexis 2014-10-05 14:40:07

+1

我很确定你想要一个'list','dict',甚至是一个单独的类而不是16个单一的属性。代码会变得糟糕。 – tamasgal 2014-10-05 14:40:10

+3

Btw .:不成熟的优化是一切罪恶的根源。 – tamasgal 2014-10-05 14:40:43

回答

1

你应该使用一个列表,而不是单独的属性:

class MyClass(object): 

    def __init__(self): 
     self.attributes = [] 

有了这个,

  • 添加属性,使用self.attributes.append(...);
  • 找出有多少(非None)属性,使用len(self.attributes);
  • 参照最终的非None属性,使用self.attributes[-1];

等等。