I am trying to subclass the immutable date
class in Python, but I also need to override the __str__
method. So far, I have the following:
from datetime import date
class Year(date):
def __new__(cls, year):
return super(Year, cls).__new__(cls, year, 1, 1)
def __str__(self):
return self.st开发者_开发问答rftime('%Y')
Constructor works fine, but the __str__
method is completely ignored when I try to print the object. I have seen a few samples subclassing other immutable classes such as int
and float
. All of them were using the same convention. Am I missing something? Is there anything special for the date
object?
UPDATE:
It seems that there is nothing wrong with the code. I was trying to print a Year
object inside a Django template and since Django formats date
objects using a localizable format __str__
method was being ignored.
Add a return
to the __str__
method.
UPDATE:
I ran your updated code on my machine, and it works fine:
aj@localhost:~/so/python# cat date2.py
from datetime import date
class Year(date):
def __new__(cls, year):
return super(Year, cls).__new__(cls, year, 1, 1)
def __str__(self):
return self.strftime('%Y')
y=Year(2011)
print str(y)
aj@localhost:~/so/python# python date2.py
2011
If this is your complete code you are missing the return statement:
def __str__(self):
return self.strftime('%Y')
精彩评论