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.
>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