重新声明方法“ in”。一堂课 [英] Redeclaration of the method "in" within a class

查看:126
本文介绍了重新声明方法“ in”。一堂课的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个抽象数据类型,它会创建一个双向链接列表(不确定它的翻译是否正确)。在其中,我创建了一个方法__len__以正确的方式计算其长度,并创建了一个方法__repr__来正确表示它,但是现在我不想创建一个方法,当用户执行以下操作时:

I am creating an Abstract Data Type, which create a doubly linked list (not sure it's the correct translation). In it I have create a method __len__ to calcucate the length of it in the correct way, a method __repr__ to represent it correctly, but I wan't now to create a method which, when the user will make something like:

if foo in liste_adt

将返回正确的答案,但我不知道该用什么,因为__in__无法正常工作。

will return the correct answer, but I don't know what to use, because __in__ is not working.

谢谢,

推荐答案

您是否在寻找 __包含____

Are you looking for __contains__?


object .__ contains __(self,item)


被调用以实现成员资格测试运算符。如果 item 位于自身中,则应返回true,否则返回false。对于映射对象,应考虑映射的键而不是值或键-项对。

Called to implement membership test operators. Should return true if item is in self, false otherwise. For mapping objects, this should consider the keys of the mapping rather than the values or the key-item pairs.

对于未定义 __ contains __() ,成员资格测试首先尝试通过 __ iter __() ,然后通过 __getitem __() ,请参见 语言参考资料中的本部分

For objects that don’t define __contains__(), the membership test first tries iteration via __iter__(), then the old sequence iteration protocol via __getitem__(), see this section in the language reference.


快速示例:

>>> class Bar:
...     def __init__(self, iterable):
...         self.list = list(iterable)
...     def __contains__(self, item):
...         return item in self.list
>>>     
>>> b = Bar([1,2,3])
>>> b.list
[1, 2, 3]
>>> 4 in b
False
>>> 2 in b
True

注意:您可以在 数据模型 Python语言参考的 strong> 部分。

Note: Usually when you have this kind of doubts references can be found in the Data Model section of the The Python Language Reference.

这篇关于重新声明方法“ in”。一堂课的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆