'Python - displaying data when using classes

I am looking to work out how to get the name of the budget to appear in the output - the code creates a list (name of budget and budget amount) and appends these as list items to a main list. I realise importing the Budget class to the app file is the way of accessing functionality but I am wondering how to extract the data created within the app file so the repr

    def __repr__(self):
        return f"The budget is {self.balance}." 

can return the name of the budget in the list


I have two files: budget_app.py and another budget_class.py


The app file uses the exec function to append new items to a list

from budget_class import Budget

list = []

def createBudget(): 
    list2 = []
    addbudgetname = input("Name the budget:")
    exec1 = f"{addbudgetname} = Budget({int(input('How much to add to budget:'))})"
    exec(exec1)
    exec2 = f"list2.append({addbudgetname})"
    exec(exec2)
    return(list2)


list.append(createBudget())
list.append(createBudget())



for item in list:
    print(item)

The class file initializes the Budget

class Budget():

    class Budget():
        def __init__(self, balance):
            self.balance = balance
            
    
        def __repr__(self):
            return f"The budget is {self.balance}." 

I am trying to work out a way of getting the name of the budget to appear in the output, which is currently

How much to add to budget:60

Name the budget:apples

How much to add to budget:800

[The budget is 60.]

[The budget is 800.]


Solution 1:[1]

The class structure is suboptimal, I would suggest to make a complete refactor, something as the following:

class Budget():
    def __init__(self, balance=0, name=None, list2=[] ):
        self.balance = balance
        self.name = name
        self.list2 = list2
        
    def createBudget(self): 
        self.name = input("Name the budget:")
        self.list2.append(input("How much to add to budget:"))
    
    def add_to_balance(self, to_add):
        self.balance += to_add
        
    def __repr__(self):
        return f"The budget is {self.balance}. and the name {self.name}" 

budget1 = Budget(0,'name1',[1,2])
budget2 = Budget(4,'name2',[1,5])
budged_list = [budget1,budget2]

Now you can instantiate the class directly with the arguments or add them with your input support, you can also print the name etc.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ziur Olpa