Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a custom class be able to be received by range()?

Tags:

python

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()).

like image 576
Hotege Avatar asked Oct 14 '25 08:10

Hotege


1 Answers

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)
like image 167
Iain Shelvington Avatar answered Oct 16 '25 22:10

Iain Shelvington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!