0

I wrote a simple object oriented code with python. In first class named A I used __str__ so that I can print my objects. In another class I put those objects in obj_list. My question is, why I can print my object with class A, but when I want to print as print(my_object.obj_list) I do not get string representation of my object?

class A:
    def __init__(self, name):

        self.name = name

    def __str__(self):

        info = "My name is: " + self.name
        return info

obj_1 = A("Mike")
obj_2 = A("Jon")
obj_3 = A("Steve")

print(obj_1, obj_2, obj_3)


class B:
    def __init__(self):
        self.obj_list = [obj_1, obj_2, obj_3]


my_object = B()

print(my_object.obj_list)
1
  • Because list.__str__ only uses the __repr__ method of any objects in the string. If you want a different string representation of a list, you need to build it yourself. Commented May 7, 2019 at 16:17

1 Answer 1

1

You're overriding __str()__ method, which called when something try to convert your class to string, i.g. print(). When you create a list of objects it put references of objects in the list and that's all. If you want them to be converted to string in any case, change:

def __str__(self):

to:

def __repr__(self):
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.