Let's say I have the following class:
class Test():
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return "Objeto {} y {}".format(self.a, self.b)
The way to get a textual representation of that object is by using the method__str__
But if I also want to obtain the textual representation of its attributes, for example, if I do this:
>>> test = Test(4, 5)
>>> print(test)
'Objeto 4 y 5'
>>> print(test.a + test.b)
9
>>> print(test.a)
'Atributo a: 4'
>>> print(test.b)
'Atributo b: 5'
What options do I have to do something like this?
Well, I don't know if it's possible to get what you want, at least not with a single class. The method
__str__()
returns the representation of the object, not the attributes. Of course it is perfectly possible to format the object in such a way that its attributes are displayed as shown in your example:I think you could get what you want by using one more class that represents the integers. Something like this:
If we reproduce your tests:
Remember that in Python integers are also objects. By doing
"Objeto {} y {}".format(self.a, self.b)
so you are actually calling the methodsint.__str__()
ofa
andb
:That said, the class
Numero
could easily inherit directly fromint
and save us some definitions. We just need to override the method__str__()
so that it renders as you want: