对象比较失败

2024-06-18 14:09:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我制作了一个对象来表示原始日期(YYYYMM),这样我就可以很容易地添加/订阅(201812+1=201901)并在一系列日期上进行for循环。当加/减或比较(eq,lt)本身正常工作时,rng函数上的for循环失败:'<' not supported between instances of 'int' and 'datetyp6'

我是不是错过了一些基本的东西?我能做什么,让Python威胁像整数这样的对象

class datetyp6:

    def __init__(self, value):
        self.value = int(value)
        self.yr = int(str(value)[0:4])
        self.mt = int(str(value)[-2:])
        if len(str(value))!=6 or self.mt>12:
            raise ValueError('Invalid Date')

    def __repr__(self):
        return self.value

    def __str__(self):
        return str(self.value)

    def __add__(self, other):
        a = other // 12
        b = other % 12
        if self.mt + b > 12:
            y = self.yr + a+1
            m = self.mt + b-12
        else:
            y = self.yr + a
            m = self.mt + b           
        return int(str(y)+str(m).zfill(2))

    def __sub__(self, other):
        a = other // 12
        b = other % 12
        if self.mt - b < 0:
            y = self.yr - a - 1
            m = self.mt - b + 12
        else:
            y = self.yr - a
            m = self.mt - b           
        return int(str(y)+str(m).zfill(2))

    def __eq__(self, other):
        if hasattr(other, 'value'):
            return self.value == other.value
        return self.value == other

    def __lt__(self, other):
        if hasattr(other, 'value'):
            return self.value < other.value
        return self.value < other


def rng(min, max, step = 1):
    while min < max:
        yield min
        min = min + step

d01 = datetyp6(201610)
d12 = datetyp6(201702)

d01 < d12

for i in rng(d01, d12):
    print(i)

Tags: selfforreturnifvaluedefminint