我正在为__init__
类编写__eq__
和Photo
函数,涉及datetime
模块。但是,我不确定我已编写的__init__
函数正文以及如何测试__eq__
。
这就是我对__init__
函数所拥有的:
class Photo:
'Fields: size, pdate'
# Purpose: constructor for class Photo
# __init__: Int Int Int Int -> Photo
# Note: Function definition needs a self parameter and does not require a return statement
def __init__(self, size, year, month, day):
self.size = size
self.pdate = year + month + day
我认为我的self.pdate
错了,但我不确定我应该写什么。也许以下几点?
self.pdate = year
self.date = month
self.date = day
答案 0 :(得分:1)
从datetime module的文档中,您可以使用以下内容创建datetime.date
个对象:
from datetime import date
some_random_date = date(2013, 7, 28)
not_so_random = date.today()
对于您的用例,这是您想要影响self.pdate
属性的对象类型:
from datetime import date
class Photo:
'Fields: size, pdate'
# Purpose: constructor for class Photo
# __init__: Int Int Int Int -> Photo
# Note: Function definition needs a self parameter and does not require a return statement
def __init__(self, size, year, month, day):
self.size = size
self.pdate = date(year, month, day)
并且为了比较两个对象:
def __eq__(self, other):
# Test that other is also a Photo, left as an exercise
return self.size == other.size and self.pdate == other.pdate
def __ne__(self, other):
return self.size != other.size or self.pdate != other.pdate