5

I am trying to print an object from a list based on my class settings.

from math import *
import time

class MyClass:
    def __init__(self, name, age):
        self.name = name
        self.age = age

people = [MyClass("David",17),
MyClass("George",63),
MyClass("Zuck",12),
MyClass("Mark",18)
]

print(people[2])

But it prints out this: <main.MyClass object at 0x0000000003129128> I want it to print "Zuck"

3
  • That's the default representation, not an error. What did you want it to print? Commented Jan 18, 2019 at 20:38
  • Please update your question to include your expected output. Commented Jan 18, 2019 at 20:38
  • You haven't told Python how to print your class! This has been answered here: stackoverflow.com/questions/4932438/… Commented Jan 18, 2019 at 20:38

1 Answer 1

4

That's because your array contains objects, so when you print them, they are printed as an object representation. I realize that what you want is to print its content.

For that you have to specify how you want to present the instance when printed, using the method __str__:

from math import *
import time

class MyClass:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return "name: {}, age: {}".format(self.name, self.age)
Sign up to request clarification or add additional context in comments.

5 Comments

I wanted to do that, but i have to wait 4m
one more question , cannot the last line just be return "name: {}, age: {}".format(name, age)
You can return anything, even a constant like "Hello"
In your case, you'll get an error because age and name are instance variables so they must bu qualified with self.. I they where declared in the body of __str__(), they could be referenced without self qualified, but they would be different variables than those declared in __init__().
Oh, yeh i think i got it, im pretty new sorry for my dumbness. thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.