是否可以子类化不可变日期类并重写 __str__ 方法?
我正在尝试在 Python 中对不可变的 date
类进行子类化,但我还需要重写 __str__
方法。到目前为止,我有以下内容:
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')
构造函数工作正常,但是当我尝试打印对象时, __str__ 方法被完全忽略。我见过一些子类化其他不可变类的示例,例如 int 和 float 。他们都使用相同的约定。我错过了什么吗? date
对象有什么特别之处吗?
更新:
看起来代码没有任何问题。我试图在 Django 模板中打印一个 Year 对象,并且由于 Django 使用可本地化格式 __str__ 方法格式化 date 对象,因此被忽略。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将
return
添加到__str__
方法。更新:
我在我的机器上运行了您的更新代码,并且运行良好:
Add a
return
to the__str__
method.UPDATE:
I ran your updated code on my machine, and it works fine:
如果这是您的完整代码,则您缺少 return 语句:
If this is your complete code you are missing the return statement: