Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__str__ not working python [closed]

Tags:

python

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?

like image 321
Norton Penguinion Avatar asked Mar 08 '13 18:03

Norton Penguinion


3 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...

like image 182
mgilson Avatar answered Nov 14 '22 03:11

mgilson


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__

like image 42
the wolf Avatar answered Nov 14 '22 03:11

the wolf


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.

like image 1
Sir Digby Chicken Caesar Avatar answered Nov 14 '22 05:11

Sir Digby Chicken Caesar