我需要迭代对象内的多个属性。每个属性都初始化为 None,并且在程序过程中每个属性都将存储一个单独的对象。我需要迭代 16 个属性,条件是这些属性将按预定顺序存储对象。例如,如果属性 10 为空,则属性 11 到 16 也将为空,因此我不需要迭代任何空属性。我的最初结果是对每个属性使用“if”语句,如下所示:
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
...
基本上,我的问题是:第二个示例在迭代非空属性方面是否更有效。因为我在第二个示例中在条件内添加条件,所以我不确定哪种方法更有效。
最佳答案
您应该使用列表而不是单独的属性:
class MyClass(object):
def __init__(self):
self.attributes = []
有了这个,
- 要添加属性,请使用
self.attributes.append(...)
; - 要了解有多少个(非
None
)属性,请使用len(self.attributes)
; - 要引用最终的非
None
属性,请使用self.attributes[-1]
;
等等。
关于Python:迭代条件内的预定条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26203630/