2011-08-18 68 views
1

我写了这个代码:误差追加到一个文件,并使用一个数组

class component(object): 

     def __init__(self, 
        name = None, 
        height = None,     
        width = None): 

     self.name = name   
     self.height = height 
     self.width = width 

class system(object): 

     def __init__(self, 
        name = None,     
        lines = None, 
        *component): 

     self.name = name 
     self.component = component 

     if lines is None: 
       self.lines = [] 
     else: 
          self.lines = lines 

     def writeTOFile(self, 
         *component): 
     self.component = component 

     line =" " 
     self.lines.append(line) 

     line= "#----------------------------------------- SYSTEM ---------------------------------------#" 
     self.lines.append(line) 


Component1 = component (name = 'C1', 
         height = 500, 
         width = 400) 
Component2 = component (name = 'C2', 
         height = 600, 
         width = 700) 

system1 = system(Component1, Component2) 
system1.writeTOFile(Component1, Component2) 

,我得到的错误:

Traceback (most recent call last): 
    File "C:\Python27\Work\trial2.py", line 46, in <module> 
    system1.writeTOFile(Component1, Component2) 
    File "C:\Python27\Work\trial2.py", line 32, in writeTOFile 
    self.lines.append(line) 
AttributeError: 'component' object has no attribute 'append' 

而且我真的不知道如何解决它。

还有一种方法可以将我的system1定义为system(Component),其中component = [Component1,Component2,... Componentn]?

感谢adavance

回答

2

你得出来的东西才能在__init__

def __init__(self, *component, **kwargs): 

    self.name = kwargs.get('name') 
    self.component = component 

    self.lines = kwargs.get('lines', []) 

会工作。您需要linesname位于收集组件的*项目之后。

在Python 2,你不能然后有一个*命名的属性,所以你需要改用**kwargsget('name')get('lines')kwargs

get只是返回None如果您不提供默认设置,那么您将在此处获得self.name = None。如果要指定一个默认名称,你可以做

self.name = kwargs.get('name', 'defaultname') 

像我一样为lines

+0

谢谢。这工作得很好! – caran

1

在第32行使用self.lines.append(line)

但是线与Component2初始化类system,其类型是类component不具有所述方法append的成员。

+0

这并不告诉他如何解决这个问题。 – agf

+0

你是对的,阅读你的答案我注意到他的真正问题是顺序,并且'Component2'不应该是'lines'。我的回答是相当无用的,很抱歉 –

+0

事实上,我不明白这个错误,因为我认为append就像是python中的一个通用函数...所以我不需要在我定义的任何类中定义它。 – caran

0

问题在于,在定义system时,您在构造函数中将Component1作为line参数传递。由于python可以执行所有的操作,并且不会检查参数类型,如果操作可以合法完成的话,就会通过。

也许它会在系统中构造一个不错的主意,以检查是否给定参数lines真是类型列表中,也许写是这样的:

if lines is None or not isinstance(lines, list): 
      self.lines = [] 
    else: 
      self.lines = lines 

这样的话,你会知道的问题之前您尝试附加到非列表对象。

至于你问题的第二部分,你可以做到这一点酷似你的建议:

system1 = system([Component1, Component2, MyComponent], []) 

(如果,例如,希望使系统具有3个组件和一个空列表作为线的“控制台”)

+0

Python是完全有能力自动汇总参数列表,并没有理由传递一个空列表。 – agf