我正在为Photo
类编写__init__
和__eq__
函数,其中涉及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
从datetime模块的文档中,您可以使用以下方法创建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