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.strftime('%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
returnto the__str__method.UPDATE:
I ran your updated code on my machine, and it works fine: