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"

ikuro
  • 87
  • 5

1 Answers1

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)
HuLu ViCa
  • 5,077
  • 10
  • 43
  • 93
  • I wanted to do that, but i have to wait 4m – ikuro Jan 18 '19 at 20:48
  • one more question , cannot the last line just be `return "name: {}, age: {}".format(name, age)` – ikuro Jan 18 '19 at 20:58
  • You can return anything, even a constant like `"Hello"` – HuLu ViCa Jan 18 '19 at 20:59
  • 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__()`. – HuLu ViCa Jan 18 '19 at 21:07
  • Oh, yeh i think i got it, im pretty new sorry for my dumbness. thanks – ikuro Jan 18 '19 at 21:22