contains__ __contains__
प्रलेखनअप्रत्याशित व्यवहार .__
print set.__contains__.__doc__
x.__contains__(y) <==> y in x.
इस तरह के पूर्णांक, basestring, आदि के रूप लेकिन उपयोगकर्ता परिभाषित वस्तुओं कि __ne__
परिभाषित के लिए आदिम वस्तुओं के लिए ठीक से काम करने लगता है से प्रलेखन उधार और __eq__
विधियों, मुझे अप्रत्याशित व्यवहार मिलता है। यहां एक नमूना कोड है:
class CA(object):
def __init__(self,name):
self.name = name
def __eq__(self,other):
if self.name == other.name:
return True
return False
def __ne__(self,other):
return not self.__eq__(other)
obj1 = CA('hello')
obj2 = CA('hello')
theList = [obj1,]
theSet = set(theList)
# Test 1: list
print (obj2 in theList) # return True
# Test 2: set weird
print (obj2 in theSet) # return False unexpected
# Test 3: iterating over the set
found = False
for x in theSet:
if x == obj2:
found = True
print found # return True
# Test 4: Typcasting the set to a list
print (obj2 in list(theSet)) # return True
तो क्या यह एक बग या सुविधा है?
इस सवाल का होना चाहिए यहां स्टैक ओवरफ्लो पर प्रदर्शित होने पर: ** प्रश्न पूछने के लिए **। समस्या को चित्रित करने वाले एक छोटे से उदाहरण के साथ, बिंदु को स्पष्ट करें। जैसा कि अन्य ने यहां उत्तर दिया है, हैश मानों का उपयोग करता है या नहीं तो उन्हें सूचियों का पूर्वाग्रह मिलेगा .. – bjarneh
स्टाइल नोट: 'if cond' के बजाय 'return self.name == other.name' का उपयोग करें: वापस लौटें \ n वापसी गलत है ' – jfs