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

How can I define plain console output of a class object (vs. __str__)?

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

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

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