1

Estoy realizando un administrador de gastos. La información de cada presupuesto se almacena en una clase creada por mi llamada Account. Todas las Accounts se guardan en una lista llamada budgets. Para seleccionar una Account ya creada se pide al usuario que introduzca el nombre. El programa entonces busca el nombre introducido en la lista budgets. Aunque defino el nombre de la account con una variable string, estas no se guardan así en la lista. En la función select, he puesto un print a proposito para comprobar como se guardaban los elementos dentro de la lista budgets, y se guardan como main.Account object at 0x00000239F29477C8. Como hago para que no se guarden así? Mando programa para entender mejor.

import os
import json


import money as m
import csv


class Account:
    """

    Simulates a budget with custom percentatges for each area of spending

    """
    def __init__(self, cash, percent):
        self.cash = int(cash)
        self.percent = percent
        self.budget = {}

        for key, value in self.percent.items():
            self.budget[key] = self.cash * value / 100


    def show(self):
        "shows actual budget"
        print(self.budget)


    def spend(self, amount, category):
        """Reduces the selected amount of money from the selected category"""
        if category in self.budget.keys() and amount < self.budget[category]:
            self.budget[category] -= amount

        elif category in self.budget.keys():
            print("\nYou don't have enough money!\n")
            while True:
                res = input("Do you want to go red numbers? (Y/N) :  ")
                if res == "Y" or res == "y":
                    self.budget[category] -= amount
                    break

                if res == "N" or res == "n":
                    print("Good decision! Operation canceled :)")
                    break

        else:
            print("\nthe selected category doesn't exist")




    def earn(self, amount):
        """

        Generates the selected amount of money and divides it
        following the percentatges.

        """
        for key, value in self.percent.items():
            self.budget[key] = amount * value / 100


def create():
    """creates a new account"""
    name = input("\nSelect name for new account: ")
    cash = int(input("Select inital amount of money: "))
    percent = {}

    while True:
        key = input("Name a new category: ")
        val = int(input("Select the percentatge (1-100): "))
        percent[key] = val
        total_val = 0

        for val in percent.values():
            total_val += val

        if total_val < 100:
            print("The percentatge is smaller than 100. Add a new category")
            continue

        elif total_val == 100:
            print("The percentatge is = to 100. Creating budget")
            break

        elif total_val > 100:
            print("The percentatge cannot be greater than 100. Restarting")
            total_val = 0
            percent.clear()
            continue

    return name, cash, percent


def select(budgets):
    """Selects an existing account to work with"""
    accname = input("Select an existing account: ")
    for budget in budgets:
        print(budget)
    if accname in budgets:
        print('account succesfully changed')
        selacc = budgets(accname)
        return selacc

    else:
        print('Sorry, the selected account doesnt exist')


def save(filename, budgets):
    """Saves the changes made into the accounts"""

    with open(filename, 'w') as f_obj: 
        json.dump(budgets, f_obj)



def main():
    """Executes the main program"""

    filename = "budgets.json"

    budgets = initialize(filename)

    while True:
        a = input("Select the desired operation (h for help): ")

        if a == 'h':
            help()

        elif a == 'create':
            while True:
                accname, cash, percent = create()

                if accname in budgets:
                    print('Sorry, there is already an account with this name. ')
                    continue

                break

            accname = Account(cash, percent)
            print('Account created succesfully')
            budgets.append(accname)

        elif a == 'select':
            selacc = select(budgets)

        elif a == 'show':
            for key, value in selacc.budget:
                print(key + ' : ' + value)

        elif a == 'save':
            save(filename, budgets)
            print('account saved succesfully')

        elif a == 'exit':
            break

        else:
            print("ERROR: The input is not an operation\n")

1 respuesta 1

0

Esto: main.Account object at 0x00000239F29477C8 es una representación de un objeto instanciado por la clase Account y es la representación por defecto que usa Python, dónde se hace referencia al nombre del módulo (en este caso main), la clase base del objeto (Account) y una posición de memoria del mismo (0x00000239F29477C8).

Lo que es importante notar que la representación del objeto no es el objeto., puedes modificar esta representación, escribiendo el método __str__ si lo que buscas es generar una representación amigable para el usuario:

def __str__(self):
   return "Account.cash: {0}".format(self.cash)

El método simplemente debe retornar una cadena con la representación que quieras mostrar del mismo.

1
  • Muchas gracias, no era exactamente lo que quería pero esto me da una idea de como hacerlo. En vez de usar la variable accname para nombrar la account, lo convertiré en un atributo de la misma, y accederé a ella con la función string. ¿Seria esto más correcto?
    – dahko37
    el 1 mar. 2020 a las 11:49

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.