有没有办法在python中的用户定义的类上定义list(obj)方法?

时间:2021-12-23 16:32:50

One can can implement the method __str__(self) to return a string. Is there an __list__(self) counterpart? (__list__ doesn't work!) Is .toList() the way to go?

可以实现方法__str __(self)来返回一个字符串。是否有__list __(自我)对应物? (__ list__不起作用!).toList()的方法是什么?

1 个解决方案

#1


15  

There is no direct counterpart, but list() is implemented by iterating over the argument. So implement either the iterator protocol (__iter__()) or bound indexing (__len__() and __getitem__()).

没有直接的对应物,但是list()是通过迭代参数来实现的。因此,实现迭代器协议(__iter __())或绑定索引(__len __()和__getitem __())。

#1


15  

There is no direct counterpart, but list() is implemented by iterating over the argument. So implement either the iterator protocol (__iter__()) or bound indexing (__len__() and __getitem__()).

没有直接的对应物,但是list()是通过迭代参数来实现的。因此,实现迭代器协议(__iter __())或绑定索引(__len __()和__getitem __())。