我有一个简单的类定义如下:
class User(object):
def __init__(self, id=None, name=None):
self.id = id
self.name = name
def __contains__(self, item):
return item == self.id
使用这个类,我可以对单个实例进行简单的检查,像这样:
>>> user1 = User(1, 'name_1')
>>> 1 in user1
True
>>> 2 in user1
False
这是按预期工作的。
但如何检查一个值是否在一个User
对象列表中呢?它似乎总是返回False。
例如:
from random import randint
from pprint import pprint
users = [User(x, 'name_{}'.format(x)) for x in xrange(5)]
pprint(users, indent=4)
for x in xrange(5):
i = randint(2,6)
if i in users:
print("User already exists: {}".format(i))
else:
print("{} is not in users list. Creating new user with id: {}".format(i, i))
users.append(User(i, 'new_user{}'.format(i)))
pprint(users, indent=4)
这将创建类似于以下输出的结果:
[ 0 => name_0,
1 => name_1,
2 => name_2,
3 => name_3,
4 => name_4]
6 is not in users list. Creating new user with id: 6
6 is not in users list. Creating new user with id: 6
6 is not in users list. Creating new user with id: 6
3 is not in users list. Creating new user with id: 3
3 is not in users list. Creating new user with id: 3
[ 0 => name_0,
1 => name_1,
2 => name_2,
3 => name_3,
4 => name_4,
6 => new_user6,
6 => new_user6,
6 => new_user6,
3 => new_user3,
3 => new_user3]
问题在于id为
6
的用户应该只被创建1次,因为它之前没有被创建过。第二次和第三次尝试创建6
时应该失败。id为3
的用户根本不应该被重新创建,因为它是users
变量的初始化的一部分。我该如何修改我的
__contains__
方法以便能够正确地使用in
来与我的类的多个实例进行比较?
if any(i in u for u in users)
- khelwood__contains__
来检查ID吗?我认为像123 in user
这样的表达并不是很直观。 - Andrea Corbellini'name_1' in user1
也为True
吗? - Peter Woodid
。 - Andy