How to use the "__str__" method?

Question:

I’m diving into some Object Oriented Programming. Unfortunately, I can’t even get up to the first step: Converting classes to strings using __str__.

Here’s my code:

class Time:

    def __init__(self, hours = 0, minutes = 0, seconds = 0):
        self.hours = hours
        self.minutes = minutes
        self.seconds = seconds

    def __str__(self):
        return "basdfadsg"



time1 = Time

time1.hours = 3
time1.minutes = 23
time1.seconds = 13

print(time1)

Whenever I try:

print(time1)

it returns:

<class '__main__.Time'>

What am I doing wrong?

Asked By: Norton Penguinion

||

Answers:

you need an instance of Time. e.g. time1 = Time() (Notice the parenthesis).

As it is, you are modifying the class, not an instance of the class — And __str__ only tells python how to create strings from instances of the class, not the classes themselves…

Answered By: mgilson

Your problem is here:

time1 = Time

You are not creating an INSTANCE of class Time and passing that to time1, but instead are passing the TYPE of that class to time1.

To have this code work as you want, simply call the object constructor:

time1 = Time()

You may be thinking “Why would anyone ever need a variable to hold a TYPE instead of an INSTANCE?” Well, in Python, class definitions (and almost everything else) are first class objects that can be modified at runtime allowing members and member functions to be dynamically added/removed from the class definition. Have fun pythoning, it’s truly a blast.

IF you really are trying to have a __str__ or __repr__ for a class vs an instance of the class, you need to use metaclasses this way:

>>> class Test(type):
...    def __repr__(self):
...       return 'Test is my name'
... 
>>> class MT(object):
...    __metaclass__=Test
... 
>>> print MT
Test is my name

But, as others have said, it is more likely that you are not referring to an instance of Time by calling __init__

Answered By: the wolf
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.