如何在自定义类中创建和比较日期时间



我正在为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

相关内容

  • 没有找到相关文章

最新更新