2

I have a python object which stores details of countries, what method should I implement to allow running the object into len(ObjectInstance)?

For example, I want to count all the countries in the instance and I must use len() the function because its a third party call/external.

How can I implement a method that would be called when len() is executed against the instance?

alecxe
  • 414,977
  • 106
  • 935
  • 1,083
Mo J. Mughrabi
  • 5,969
  • 14
  • 68
  • 130

1 Answers1

4

Implement __len__() magic method:

>>> class A():
...     def __len__(self):
...         return 100
... 
>>> a = A()
>>> len(a)
100

Also see:

Community
  • 1
  • 1
alecxe
  • 414,977
  • 106
  • 935
  • 1,083