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

时间:2015-07-21 21:57:38

标签: python class datetime

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

1 个答案:

答案 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