Skip to content

Instantly share code, notes, and snippets.

@Pinacolada64
Created December 15, 2021 22:05
Show Gist options
  • Save Pinacolada64/3b8ff0833e322befc57ea7c4f2225c75 to your computer and use it in GitHub Desktop.
Save Pinacolada64/3b8ff0833e322befc57ea7c4f2225c75 to your computer and use it in GitHub Desktop.
is printing 'age' property with __str__ possible?
class Player(object):
def __init__(self, age: int):
self.age = age
def print_age(self):
# FIXME: can calling p.print_age() be simplified by instead using a __str__ method?
if self.age == 0:
return 'Unknown'
else:
return f'{self.age} years'
def __str__(self, age):
return f'something {self.age}'
if __name__ == '__main__':
p = Player(age=30)
print(f'{p.print_age()}')
p = Player(age=0)
print(f'{p.print_age()}')
# what I would like to do is have a __str__ method handle this:
# print(f'{p.age}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment