Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printing different values within class in Python

I’ve been trying to get the method to print out the specific attribute within class. Although I’ve already used _str_ for another thing, and for now it returns the location of my method, which is useless to me.

class Account():

    def __init__(self,name,value):

        self.name = name
        self.value = value


    
    def __str__(self):
        return f'Account owner: {self.name}\nAccount balance: ${self.value}'

    def owner(self):
        return self.name

    def balance(self):
        return self.balance

You get the idea, I wanted it to return the name user passed in Account class.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’d do it like this:

class Account():

    def __init__(self,name,value):
        self.name = name
        self.value = value

    def __str__(self):
        return f'Account owner: {self.Owner}\nAccount balance: ${self.Balance}'

    @property  # note here a property to make external access more obvious
    def Owner(self):
        return self.name

    @property  # note here a property to make external access more obvious
    def Balance(self):
        return self.value  # this is the property you need


if __name__ == '__main__':  # a very simple test, common idiom
    acct = Account("TomServo", 100.40)
    print(acct)

OUTPUT:

Account owner: TomServo

Account balance: $100.4

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading