Python - UnboundLocal Error - class instance vanishes after several function calls within class

Hi, first ever attempts on Python - thanks in advance.

I am calling def:“Add_expense” repeatedly from def:“Budget”.

My intention was to create a class instance A = category(name) with the parameters shown under init. This instance is called only once, because on subsequent calls the “name” value is recognized, and this step will be skipped.

And then a class function A.expense(qty, descr) that strings together the quantities and descriptions into the self.lists() in init after several function calls, and also cumulates the total balance in self.dict()={‘bal’:0}

However, after the 2nd run of def:“Add_expense”, when I call A.expense(qty, descr) I get the following error:
Exception has occurred: UnboundLocalError
cannot access local variable ‘A’ where it is not associated with a value

Sorry, I’ve searched far and wide, but I’m completely stuck.

thank you!

class category:

    options = dict() 
    keys = list()
        
    def __init__(self, name):
        self.name = name
        self.qties = list()
        self.descrs = list()
        self.bal = {'bal':0}

    def expense(self, qty, descr):
        self.qties.append(qty)
        self.descrs.append(descr)
        balance = self.bal.get('bal')
        balance += qty
        self.bal['bal'] = balance
        print(self.name, self.qties, self.descrs, self.bal.get('bal'))


    def budget():
            # [...] More options will be added here.
        category.Add_expense()

    def Add_expense():
        
        indx = 0
        exist = 0
        
        name = input('Name: ')
        descr = input('Description: ')
        qty = int(input('Quantity: '))

        if len(category.options) > 0:
            for i in range(0,len(category.options)+1):
                if category.options.get(i) == name: exist = 1
        if exist != 1:
            A = category(name)
            category.options.update({indx:name})
            category.keys.append(name)
        elif exist == 1:
            exist = 0
        A.expense(qty, descr)

        category.budget()

category.budget()

A probably doesn’t exist here

hi Jeremy

right - I thought that by setting “A = category(name)” once, I would be able to call “A.expense()” as many times as needed between function calls.

Any idea for a workaround here?

thanks,

You can store the data as a property of the object

sorry, can I ask you for an example?
thanks

You have 6 examples here

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.