When defining my own class, I can overwrite the __str__ to define its print(my_class) behavior. What do I have to do to overwrite the behavior when just calling an my_class object?
What I get:
> obj = my_class("ABC") # define
> print(obj) # call with print
'my class with ABC'
> obj # call obj only
'<__console__.my_class object at 0x7fedf752398532d9d0>'
What I want (e.g. obj returning the same as print(obj) or some other manually defined text).
> obj # when obj is called plainly, I want to define its default
'my class with ABC (or some other default representation of the class object)'
With:
class my_class:
def __init__(self, some_string_argument)
self.some_string = some_string_argument
def __str__(self): #
return f"my_class with {self.some_string}"
>Solution :
Magic method __repr__ is the one. But this is discouraged.
In general __str__ should be understandable for the end user and __repr__ should return a string which when passed to eval would produce a valid instance of the object for which it’s defined.
class A:
def __repr__(self):
return "I'm A!"
a = A()
a # This will print "I'm A!"
What it should/could be:
class A:
def __repr__(self):
return "A()"
a = A()
a_repr = a.__repr__()
b = eval(a_repr) # "b" is an instance of class A in this case