【发布时间】:2018-05-11 15:44:55
【问题描述】:
我是 Python 的新手,我正在尝试编写一个类,它只存储两个属性,其中一个是数字,另一个是日期时间对象。虽然我也想在将date 存储为日期时间的同时,使用“dd.mm.yyyy”之类的字符串对其进行初始化和输出。所以我走了:
class MyClass:
number = None
date = None
def __init__(self, params):
self.number = params["number"]
self.date = params["date"]
@property
def date(self):
return datetime.datetime.strftime(self.date, '%d.%m.%Y')
@date.setter
def date(self, value):
self.date = datetime.datetime.strptime(value, '%d.%m.%Y')
def get_vars(self):
return vars(self)
但在运行时@property 指向self.date 并说:Expected type 'datetime', got 'str' instead。当它在设置时要转换为日期时,它怎么能得到一个字符串。为什么会这样?困惑。
例如:
>>> MyClass({'number': 42, 'date': '28.12.2017'})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 8, in __init__
File "<string>", line 16, in date
File "<string>", line 16, in date
TypeError: strptime() argument 1 must be str, not datetime.datetime
【问题讨论】:
-
请务必包含完整回溯和创建
MyClass实例的代码。我可以在这个特定的、有限的情况下确切地找出一定发生的事情,但是回溯可以让未来的访问者更容易查看他们是否有同样的问题。
标签: python python-3.x oop datetime properties