KeyError 发表于 2023-1-17 17:17:31

实现range类

本帖最后由 KeyError 于 2023-1-17 17:18 编辑

>>> #shell
>>> help(range)
Help on class range in module builtins:

class range(object)
|range(stop) -> range object
|range(start, stop[, step]) -> range object
|
|Return an object that produces a sequence of integers from start (inclusive)
|to stop (exclusive) by step.range(i, j) produces i, i+1, i+2, ..., j-1.
|start defaults to 0, and stop is omitted!range(4) produces 0, 1, 2, 3.
|These are exactly the valid indices for a list of 4 elements.
|When step is given, it specifies the increment (or decrement).
|
|Methods defined here:
|
|__bool__(self, /)
|      self != 0
|
|__contains__(self, key, /)
|      Return key in self.
|
|__eq__(self, value, /)
|      Return self==value.
|
|__ge__(self, value, /)
|      Return self>=value.
|
|__getattribute__(self, name, /)
|      Return getattr(self, name).
|
|__getitem__(self, key, /)
|      Return self.
|
|__gt__(self, value, /)
|      Return self>value.
|
|__hash__(self, /)
|      Return hash(self).
|
|__iter__(self, /)
|      Implement iter(self).
|
|__le__(self, value, /)
|      Return self<=value.
|
|__len__(self, /)
|      Return len(self).
|
|__lt__(self, value, /)
|      Return self<value.
|
|__ne__(self, value, /)
|      Return self!=value.
|
|__reduce__(...)
|      Helper for pickle.
|
|__repr__(self, /)
|      Return repr(self).
|
|__reversed__(...)
|      Return a reverse iterator.
|
|count(...)
|      rangeobject.count(value) -> integer -- return number of occurrences of value
|
|index(...)
|      rangeobject.index(value) -> integer -- return index of value.
|      Raise ValueError if the value is not present.
|
|----------------------------------------------------------------------
|Static methods defined here:
|
|__new__(*args, **kwargs) from builtins.type
|      Create and return a new object.See help(type) for accurate signature.
|
|----------------------------------------------------------------------
|Data descriptors defined here:
|
|start
|
|step
|
|stop
>>>

所以,我们今天来实现range类的基本功能{:10_298:}

根据小甲鱼老师的生成器,代码显而易见

>>> class range:
    def __init__(self, stop, /):
      self.stop = stop
      self.num = -1
    def __iter__(self):
      return self
    def __next__(self):
      self.num += 1
      if self.num >= self.stop:
            raise StopIteration
      return self.num
>>>

但是这样并不能传入开始值和步长{:10_249:}

问题是如果只有一个参数,它应该是结束值,但有两个及以上,应该按开始值,结束值,步长的顺序传入。

两千年后,我终于想到了办法!

class range:
    def __init__(self, *args, /):
      if len(args) == 1:
            self.stop = args
            self.num = -1
            self.add = 1
      elif len(args) == 2:
            self.stop = args
            self.num = args - 1
            self.add = 1
         elif len(args) == 3:
            self.stop = args
            self.num = args - 1
            self.add = args
         elif len(args) == 0:
            raise TypeError("range expected at 1 argument, got 0")
         else:
            raise TypeError(f"range expexct ed at 3 argument, got {len(args)}")
    def __iter__(self):
      return self
    def __next__(self):
      self.num += self.add
      if self.num >= self.stop:
            raise StopIteration
      return self.num
>>>
>>> for i in range(1, 10, 2):
      print(i)

1
3
5
7
9
>>>

完美!{:10_279:}

match123_xbd 发表于 2023-4-8 15:38:03

{:5_106:}
页: [1]
查看完整版本: 实现range类