我不知道如何访问另一个类对象中的类对象。 给出一个由“
”组成的“最佳结果”类如下面的代码所示。我的问题是:
(A)在“Best Result”类def“SetColors”中,如何将self.colors初始化为颜色大小?下面的代码似乎分配了空列表,所以当我将参数“colors”复制到“self.colors”时,它表示“索引超出范围”。深透镜是否正确?
self.colors = list(colors)
for i in range(0, len(colors)):
self.colors[i]= copy.deepcopy(colors[i])
(B)如何在“Best Result”类中设置并获取类“Color”的数组?
感谢您的评论,我尝试优化代码并获得以下问题的答案。
import copy
class Color(object):
__elems__ = "num", "nodelist"
def __init__(self):
self.num = 0
self.nodelist = []
def items(self):
return [
(field_name, getattr(self, field_name))
for field_name in self.__elems__]
class BestResult(object):
__elems__ = "objfunc", "colors"
def __init__(self):
self.objfunc = 0
self.colors = []
def setObjFunc(self, value):
if value < self.objfunc:
self.objfunc = value
def getObjFunc(self):
return self.objfunc
def setColors(self, colors):
# Q1: How to initialize self.colors to size of colors? Index out of range now as self.colors has zero length.
self.colors = list(colors)
for i in range(0, len(colors)):
# Q2: Is this the right way to copy class?
self.colors[i]= copy.deepcopy(colors[i])
def getColors(self):
return self.colors
def funcA():
br = []
br.append(BestResult())
colors = []
colors.append(Color())
colors[0].num = 5
colors[0].nodelist = [10, 20 , 30 , 40, 50]
colors.append(Color())
colors[1].num = 2
colors[1].nodelist = [6, 7]
br[0].setObjFunc(-100)
# Q3: How to set colors[0] and colors[1] into br's colors?
br[0].setColors(colors)
print("br=%d" %br[0].getObjFunc())
# Q4 How to retrieve each elements of (num & nodelist) in br[0].colors
res = br[0].getColors()
print res[0].num
print res[0].nodelist
print res[1].num
print res[1].nodelist
if __name__ == '__main__':
funcA()