2013-04-04 50 views
0

我試圖通過使潔具對象的列表,以收據程序中的功能。我通過製作來實現這個目的和功能,如:使用類

class ware(object): 

    def __init__(self, code, name, price, quantity): 
     self.code= code 
     self.name = name 
     self.price = price  
     self.quantity= quantity 

    def code (self): 
     return self.code 

def my_wares(): 
    wares_from_file= open("wares.txt", "r") 
    list_of_wares= [] 
    for line in wares_from file: 
     every_ware1= line 
     every_ware2= varje_vara1.split("/") 
     wares= ware(every_ware2[0],every_ware2[1], every_ware2[2], every_ware2[3]) 
     list_of_wares.append(varorna) 

    list_of_wares.sort() 
    return(list_of_wares) 

後,我已經做了我的對象列表中,我通過調用我的函數的主要功能:

def main(): 
    all_wares = my_wares() 

現在我需要用這個裏面的另一個類方法潔具對象列表,我想這樣做:

class receipt_part(ware): 
    def __init__(self, kod, namn, pris, butik_antal): 
     ware.__init__(self, code, name, price, quantity) 
     self.price_toal= 0 
     self.customer_quantity= 0 

    def shop_ware(kod): 
     wares_quantity= input("how many wares does the customer wants?") 
     self.name= all_wares[1] 
     self.price= all_wares[2] 
     peice_total+= all_wares[3]*wares_quantity 
     customer_quantity+= int(wares_quantity) 
     quantity= int(all_wares[4]) - int(wares_quantity) 
     __str__() 

但它說,all_wares沒有定義,但我在主函數中使用它,這是爲什麼?

+0

請解決您的壓痕 – wRAR 2013-04-04 15:48:47

+0

看看collections.namedtuple(),這是一種統一的方式來定義「類潔具」(這應該是根據PEP 8類潔具)。 – 2013-04-04 17:21:09

回答

3

在一個函數中不能定義一個變量,在即使第一個函數被調用main另一個函數中使用它。您需要明確地將該變量傳遞給第二個函數。

+0

或全球my_global_var' – 2013-04-04 15:54:22

+0

@JoranBeasley這是一個壞主意的主要附加'頂部。當然,你甚至還有其他方法可以做到這一點,但它們通常不是最好的方法。 – wRAR 2013-04-04 16:00:58

+0

我並沒有說這是一個偉大的想法...但它看起來像他想的全局變量,並說實話有次在那裏全局意義的,儘管一般人壞主意岬(授予合法的案件幾乎沒有) – 2013-04-04 17:00:14