我有一个利用浮动范围的类。除了我的 getitem ()方法之外,其他所有方法都可以正常工作。我正在尝试遵循以下步骤:
Python: Implementing slicing in __getitem__
这是它需要做的\就其调用而言而言:
>>> my_range = float_range(0.5, 7, 0.75)
>>> list(my_range[:2])
[0.5, 1.25]
>>> list(my_range[-1:100])
[6.5]
>>> list(my_range[-3:])
[5.0, 5.75, 6.5]
>>> list(my_range[::2])
[0.5, 2.0, 3.5, 5.0, 6.5]
到目前为止,我的代码:
from math import ceil
class float_range:
def __init__(self, start, stop=None, step=1.0):
if stop is None:
start, stop = 0, start
(self.start, self.stop, self.step) = (start, stop, step)
def __len__(self):
return max(ceil((self.stop-self.start) / self.step), 0)
def __iter__(self):
i = self.start
for _ in range(len(self)):
yield i
i += self.step
def __reversed__(self):
i = self.start + (len(self)-1) * self.step
for _ in range(len(self)):
yield i
i -= self.step
def __getitem__(self, given):
if isinstance(given, slice):
i = self.start
for _ in range(self.stop):
yield i
i += self.step
for n in float_range(0.5, 2.5, 0.5):
print(n)
print(list(float_range(3.5, 0, -1)))
for n in float_range(0.0, 3.0):
print(n)
for n in float_range(3.0):
print(n)
print(len(float_range(0.5, 2.5, 0.5)))
print(list(reversed(float_range(0.5, 2.5, 0.5))))
floater = float_range(1, 10, 2)
print(len(floater))
for item in floater:
print(item)
reverse_range = reversed(float_range(0.5, 7, 0.75))
print(list(reverse_range))
# [6.5, 5.75, 5.0, 4.25, 3.5, 2.75, 2.0, 1.25, 0.5]
my_range = float_range(0.5, 7, 0.75)
print(list(my_range[:2]))
我知道__getitem()方法中的for循环是错误的,但我只是不明白如何使它停止使用传入的切片符号。
输出:
0.5
1.0
1.5
2.0
[3.5, 2.5, 1.5, 0.5]
0.0
1.0
2.0
0
1.0
2.0
4
[2.0, 1.5, 1.0, 0.5]
5
1
3
5
7
9
[6.5, 5.75, 5.0, 4.25, 3.5, 2.75, 2.0, 1.25, 0.5]
[0.5, 1.25, 2.0, 2.75, 3.5, 4.25, 5.0]