2014-02-19 40 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