Home > Net >  How to print my class and not get memory reference
How to print my class and not get memory reference

Time:12-01

I have a class called Pension, with attributes like a person's name, age, savings and a growth rate.

I have a class method which calculates the person's total savings at retirement year.

Under my main function, I want to print the class to see if my code is working as intended, but I don't know how to do as I only get the memory reference when printing.

How can I print the class instance, so that it goes through all its attributes and runs the function result, and prints the result? Worth to note; to run the function 'result' which calculates the total pension, the growth rate is user inputted and in a function of its own (and is run in main())

For example, if I try to print the 2nd last line: print(pensions) I only get the memory reference. So in this case, if a person (the data for which I read in from a file) has saved up 1000 dollars (using my result method), I would like that fact to be printed into a list.

This is my code:

class Pension:
    def __init__(self, name,age,savings,growth):
        self.name = name
        self.age = age
        self.savings = savings
        self.growth = growth



    def result(self):
        amount=self.savings
        rate=1 (self.growth/100)
        years=65-self.age
        return (amount * (1 - pow(rate, years))) / (1 - rate)
        

def convert(elem: str):
    if not elem.isdigit():
        return elem
    return float(elem)


def convert_row(r: list) -> list:
   return [convert(e) for e in r]

def get_growth(msg: str = "Enter growth rate: "):
    return float((input(msg).strip()))


def main():
    with open('personer.txt') as f:
        raw_data = f.readlines()

    data = [row.split("/") for row in raw_data]
    data = [convert_row(row) for row in data]

    pensions = [Pension(*i, get_growth()) for i in data]
    

main()

CodePudding user response:

From the Pension class object's perspective it doesn't actually matter how is the growth provided. Also in this case maybe it's worth to make the result a property, then there's no need to call it as a function (just access like any other property, but the values will be calculated "dynamically"). You can customize the __str__ method to return any str representation of your object.

class Pension:
    def __init__(self, name,age,savings,growth):
        self.name = name
        self.age = age
        self.savings = savings
        self.growth = growth
        self._result = result

    @property
    def result(self):
        amount=self.savings
        rate=1 (self.growth/100)
        years=65-self.age
        return (amount * (1 - pow(rate, years))) / (1 - rate)


    def __str__(self):
        return f"Pension:\n{self.amount=}\n{self.age=}\n{self.savings}\n{self.growth=}\n{self.result}"

And then just:

for p in pensions:
    print(p)
  • Related