我有一个python对象,它存储国家的详细信息,我应该实现什么方法来允许将对象运行到len(ObjectInstance)?
例如,我想计算实例中的所有国家,我必须使用len()函数,因为它是第三方调用/external。
如何实现对实例执行len()时将调用的方法?

最佳答案

实施魔法方法:

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

另见:
Making Custom SequencesPython魔法方法指南
Why does python use 'magic methods'?
difference between len() and .__len__()?

关于python - python对象接受len函数对其运行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22591439/

10-12 23:06
查看更多