range() in Python seems to accept integer as parameter only. How to make range() accept a custom class as parameter?
I've defined a class such as:
class MyInteger:
def __init__(self, a:int):
self._a = a
def __int__(self):
return self._a
And I tried:
n = MyInteger(5)
for i in range(n):
print(i)
It always causes 'object cannot be interpreted as an integer' whether or not I defined __int__.
Is there any way to solve this problem?
range(n)
cannot be changed to range(int(n))
or range(n.get_int())
.
Implement __index__
to allow your class instances to be interpreted as an int
class MyInteger:
def __init__(self, a:int):
self._a = a
def __index__(self):
return self._a
n = MyInteger(5)
for i in range(n):
print(i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With