Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print/return a class in python? [duplicate]

Possible Duplicate:
Python: How to print a class or objects of class using print()?

I currently have this code:

class Track(object):
    def __init__(self,artist,title,album=None):
        self.artist = artist
        self.title = title
        self.album = album

    def __str__(self):
        return self.title + self.artist + self.album

Now when I put something like Track('Kanye West','Roses','Late Registration') into the terminal I get <__main__.Track object at 0x10f3e0c50> How can I get it to return or print the value at that place?

I'm new to programming and especially new to 'object oriented programming', so my question is what exactly is a class? How do I define a function within a class?

like image 728
iamtesla Avatar asked Aug 24 '26 10:08

iamtesla


2 Answers

You should define __repr__ method:

class Track(object):

    ...

    def __repr__(self):
        return ('Track(artist=%s album=%s title=%s)' 
                % (repr(self.artist), repr(self.title), repr(self.album)))

Now you can see representation of object in terminal:

>>> Track('Kanye West','Roses','Late Registration')
Track(artist='Kanye West' album='Roses' title='Late Registration') 

Note that there is a difference between __str__ and __repr__ method:

  • __str__ needs to convert an object into a string. Calling: str(obj)
  • __repr__ - for its human readable visualization. Calling: repr(obj)

When you put into the terminal obj, python calls repr function automatically. But if you use print obj expression, python calls str function:

>>> obj
...repr of obj here...
>>> print obj
...str of obj here...

See doc for more information.

like image 200
defuz Avatar answered Aug 25 '26 23:08

defuz


Your code is fine, but you are forgetting something.

Lets say you have this class:

class Bob():
    def __init__(self, hobby):
        self.hobby = hobby

In the console you would make a Bob class with a hobby like this:

a = Bob("skiing")

then to get Bob's hobby you can do:

print a.hobby

now - back to your problem, you did Track('Kanye West','Roses','Late Registration')

you created an object, but you did not assign the object to a variable. so your result is the object itself... you could simply print the object, which will invoke the __str__ method. so...

print Track('Kanye West','Roses','Late Registration')

would work, but if you wanted to do it a bit nicer. (for example)

a = Track('Kanye West','Roses','Late Registration')
print a.title
print a.artist
print a.album
like image 36
Inbar Rose Avatar answered Aug 26 '26 00:08

Inbar Rose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!