我制作了一个表示原始日期(YYYYMM)的对象,以便可以轻松添加/订阅(201812 + 1 = 201901)并在其中的一个范围内进行循环。当加/减或比较(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)