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()

现在我需要在另一个类方法中使用这个 ware 对象列表,我尝试这样做:

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 没有定义,虽然我在我的 main 函数中使用了它,这是为什么呢?

4

1 回答 1

3

即使调用了第一个函数,您也不能在一个函数中定义变量并在另一个函数中使用它main。您需要将变量显式传递给第二个函数。

于 2013-04-04T15:50:33.167 回答