1

我对python比较陌生。我有一个 Time 类,我想检查一组 Time 对象是否包含另一组 Time 对象。

a = {Time(10,10)} 
print {Time(10,10)}.issubset(a) >> "result is False"
for i in a:
    print i in a >> "result is True"

在课堂上,我已经实现了这些方法

def to_min(self):
    return self.h * 60 + self.m
def __cmp__(self, other):
    if isinstance(other, Time):
        if self.to_min() > other.to_min():
            return 1
        else:
            if self.to_min() == other.to_min():
                return 0
            else:
                return -1
def __eq__(self, other):
    if isinstance(other, Time):
        if self.to_min() == other.to_min():
            return True
        else:
            return False
def __gt__(self, other):
    return self.to_min() > other.to_min()
def __ge__(self, other):
    return self.to_min() >= other.to_min()
def __lt__(self, other):
    return self.to_min() < other.to_min()
def __le__(self, other):
    return self.to_min() <= other.to_min()
def __str__ (self):
    return str(self.h) + ":" + str(self.m)
def __hash__(self):
    return self.to_min()

我想知道我还应该实现或更改什么以使以下代码行打印为真。我已经阅读了=at 有一个contains方法。但我不会检查一个 Time 对象是否包含其他组件。

a = {Time(10,10)} 
print {Time(10,10)}.issubset(a) >>
4

1 回答 1

0

我换了这个

 self.to_min() == other.to_min()

有了这个

 self.__hash__() == other.__hash__()

并且还编辑了eq以返回布尔值,而不是整数现在它可以工作了,我仍然想知道。无论如何,如果有人感兴趣,这是完整的代码:

class Time(object):
'''
classdocs
'''


def __init__(self, h, m):
    if isinstance(h, int) and isinstance(h, int):
        self.m = m
        self.h = h
        if(self.m >= 60):
            self.h += self.m // 60
            self.m %= 60
def __add__(self, m):

    return Time(self.h, self.m + m)
def to_min(self):
    return self.h * 60 + self.m
def __cmp__(self, other):
    print "__cmp__"
    if isinstance(other, Time):
        if self.to_min() > other.to_min():
            return 1
        else:
            if self.__hash__() == other.__hash__():
                return 0
            else:
                return -1
def __eq__(self, other):
    print "__eq__"
    if isinstance(other, Time):
        if self.to_min() == other.to_min():
            return True
        else:
            return False
def __gt__(self, other):
    return self.to_min() > other.to_min()
def __ge__(self, other):
    return self.to_min() >= other.to_min()
def __lt__(self, other):
    return self.to_min() < other.to_min()
def __le__(self, other):
    return self.to_min() <= other.to_min()
def __str__ (self):
    return str(self.h) + ":" + str(self.m)
def __hash__(self):
    print "__hash__"
    return self.to_min()
    # return 1
def __ne__(self, other):
    print "__ne__"
    return not self == other



# a = set([Time(10,10), Time(10,20)])
# b = set([Time(10,10)])
# print a in set([b])
a = {Time(10,10)} 
print {Time(10,10)}.issubset(a) 
# print b.issubset( a)
# for i in a:
#     print i in a
于 2013-07-19T23:32:16.497 回答