2014-02-19 39 views
1

我在進行數據存儲和檢索時遇到問題。類臨時數據存儲區,Python

什麼,我想要做的本質是創造盒A和乙欄

每個包廂有不同的描述,並在他們的項目清單,它們是由Box_handler訪問。

基本上是:

class Box_Handler(object): 
    def __init__(self,which_box): 
     self.which_box = which_box 
    def call_box(self): 
     if self.which_box == 'A': 
      self.contents = Box_A().load() 
     elif self.which_box == 'B': 
      self.contents = Box_B().load() 
     print(self.contents) 

class Box_A(object): 
    def __init__(self): 
     self.contents = ['banana,apple,pear'] 

    def box_store(self): 
     self.contents = self.contents+['guava'] 

    def load(self): 
     return self.contents 

class Box_B(object): 
    def __init__(self): 
     self.contents = ['orange,fig,grape'] 

    def box_store(self): 
     self.contents = self.contents+['guava'] 

    def load(self): 
     return self.contents 

A = Box_A() 
B = Box_B() 
A.box_store() 
B.box_store() 
Box_Handler('A').call_box() 
Box_Handler('B').call_box() 

它不打印番石榴,因爲每次類運行時,它觸發初始化,所以我想將在初始化器那永遠只能運行一次,但我遇到了同樣的問題需要一個變量來激活初始化程序

有沒有人有工作? 我聽說泡菜,但如果我有一千盒,我需要一千個文件??!

對不起,如果太簡單了,但我似乎無法找到最簡單的方法。

回答

0

Box_Handlercall_box中,您每次都在創建新對象,並且您沒有通過調用box_store來添加guava。爲了解決這個問題,你可以這樣

def call_box(self): 
    self.contents = self.which_box.load() 
    print(self.contents) 

改變call_box,你必須創建Box_Handler對象,這樣

Box_Handler(A).call_box() 
Box_Handler(B).call_box() 

這個固定輸出變爲

['banana,apple,pear', 'guava'] 
['orange,fig,grape', 'guava'] 

如果您其實想擁有水果清單,你應該像這樣初始化contents

self.contents = ['banana', 'apple', 'pear'] # list of strings 
... 
self.contents = ['orange', 'fig', 'grape']  # list of strings 

而不是像你在你的程序中所做的那樣。因爲,

self.contents = ['banana,apple,pear'] # list of a comma separated single string 

隨着這種變化時,輸出變成這樣

['banana', 'apple', 'pear', 'guava'] 
['orange', 'fig', 'grape', 'guava'] 
+0

這肯定回答OP的問題,但我覺得好像有是被忽視的一個嚴重缺陷的設計。 – SethMMorton

+0

@SethMMorton哦,我明白你的意思了。更新了我的答案。請立即檢查。 – thefourtheye

+0

謝謝你的答案,它確實工作。 但是爲什麼?不是, self.contents = Box_B()。load() 與 相同self.contents = self.which_box.load()?? – NewbieGamer