Reputation: 161
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?
Upvotes: 7
Views: 14766
Reputation: 33
A 2023 answer. Try using __repr__
instead of __str__
. According to this answer, I am not attempting to print out an instance but a type. However, in my code I am creating instances and appending to a list and when I want to print out that list __repr__
is being invoked, should it be present.
Upvotes: 0
Reputation: 35572
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__
Upvotes: 2
Reputation: 3133
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.
Upvotes: 1
Reputation: 310237
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...
Upvotes: 13