通常(至少在oop中),您可以按照您想要的方式来塑造对象。name in USERNAMES不是大小写不敏感的,所以USERNAMES需要改变:
class NameList(object):
def __init__(self, names):
self.names = names
def __contains__(self, name): # implements `in`
return name.lower() in (n.lower() for n in self.names)
def add(self, name):
self.names.append(name)
# now this works
usernames = NameList(USERNAMES)
print someone in usernames
这样做的好处是,它为许多改进开辟了道路,而无需更改类之外的任何代码。例如,您可以将self.names更改为一个集以更快地查找,或者只计算一次(n.lower() for n in self.names)并将其存储在类中,等等……
class CaseInsensitiveDict(dict):
''' requests special dicts are case insensitive when using the in operator,
this implements a similar behaviour'''
def __contains__(self, name): # implements `in`
return name.casefold() in (n.casefold() for n in self.keys())
现在你可以像USERNAMESDICT = CaseInsensitiveDict(USERNAMESDICT)这样转换字典并使用if 'MICHAEL89' in USERNAMESDICT: