2011-08-18 65 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