有没有办法制作"[X(),Y(),Z()]中的X()"?返回True吗? [英] Is there a way to make "X() in [X(), Y(), Z()]" return True?

查看:74
本文介绍了有没有办法制作"[X(),Y(),Z()]中的X()"?返回True吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的这个项目中有一个自定义对象,称为Page.页面的识别功能是其标题.通常通过调用 Wiki.page创建页面 Wiki.category Wiki.template ,或通过其他方法(例如 Wiki.random . (我建议您在继续操作之前先看一下.)

I have a custom object in this project of mine, called Page. A Page's identifying feature is its title. A Page is normally created by calling Wiki.page, Wiki.category, or Wiki.template, or by generating them from other methods like Wiki.random. (I recommend you look a little bit at what that is before going on.)

有时,该模块的用户可能想要生成一些Pages,并将该生成器转换为普通的list.在获得该页面列表之后,他们可能想要检查所获得的另一个页面是否在该列表中.但是,这是

Sometimes, users of this module might want to generate some Pages and convert that generator into a normal list. After they obtain that list of Pages, they might want to check if another page they got is in that list. However, this:

>>> wp = mw_api_client.Wiki('https://en.wikipedia.org/w/api.php')
>>> wp.page('title') in [wp.page('title'),
                         wp.page('not this'),
                         wp.page('not this either')]
False

应该为True,而不是False,因为其中有 包含title标题"的页面.我可以使用一种魔术方法来实现这一目标吗?我已经尝试使用__eq__(用于相等性)和__hash__(用于散列检查)(

should be True, not False, because there is a page with the title "title" in it. Is there a magic method I can use to make that True? I already tried using __eq__ (for equality) and __hash__ (for hash checking) (commit), but neither seemed to do the trick. Do lists simply use identity? Or is there something else I'm missing? How do I do this properly?

推荐答案

等等,现在可以了!

>>> w = mw.Wiki('https://en.wikipedia.org/w/api.php')
>>> a = [w.page('hi'), w.page('ih'), w.page('ij')]
>>> w.page('hi') in a
True

好的,我不知道以前出了什么问题.现在解决了.我将保留 Attie answer .

Okay, I don't know what went wrong before. This is solved now. I'll keep Attie's answer in mind, though.

这篇关于有没有办法制作"[X(),Y(),Z()]中的X()"?返回True吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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