पायथन x > y > z
जैसे अभिव्यक्तियों की अनुमति देता है, जो दस्तावेज़ों के अनुसार (x > y) and (y > z)
के बराबर है y
को छोड़कर केवल एक बार मूल्यांकन किया जाता है। (https://docs.python.org/3/reference/expressions.html)कस्टम जंजीर तुलना
हालांकि, अगर मैं तुलनात्मक कार्यों को कस्टमाइज़ करता हूं तो यह तोड़ने लगता है। जैसे मैं निम्नलिखित वर्ग है लगता है: (। बड़े ब्लॉक के लिए क्षमा याचना, लेकिन एक बार आप __eq__
विधि पढ़ा है, बाकी मामूली बात है)
class CompareList(list):
def __repr__(self):
return "CompareList([" + ",".join(str(x) for x in self) + "])"
def __eq__(self, other):
if isinstance(other, list):
return CompareList(self[idx] == other[idx] for idx in xrange(len(self)))
else:
return CompareList(x == other for x in self)
def __ne__(self, other):
if isinstance(other, list):
return CompareList(self[idx] != other[idx] for idx in xrange(len(self)))
else:
return CompareList(x != other for x in self)
def __gt__(self, other):
if isinstance(other, list):
return CompareList(self[idx] > other[idx] for idx in xrange(len(self)))
else:
return CompareList(x > other for x in self)
def __ge__(self, other):
if isinstance(other, list):
return CompareList(self[idx] >= other[idx] for idx in xrange(len(self)))
else:
return CompareList(x >= other for x in self)
def __lt__(self, other):
if isinstance(other, list):
return CompareList(self[idx] < other[idx] for idx in xrange(len(self)))
else:
return CompareList(x < other for x in self)
def __le__(self, other):
if isinstance(other, list):
return CompareList(self[idx] <= other[idx] for idx in xrange(len(self)))
else:
return CompareList(x <= other for x in self)
अब मैं CompareList([10, 5]) > CompareList([5, 10])
की मज़ेदार बातों से कर सकते हैं और इसे सही ढंग CompareList([True,False])
हालांकि, इन कार्यों के चेनिंग अच्छी तरह से काम नहीं करता है:
low = CompareList([1])
high = CompareList([2])
print(low > high > low) # returns CompareList([True])
क्यों नहीं? हुड के नीचे क्या होता है? मुझे पता है कि यह (low > high) > low
= (False > low)
के बराबर नहीं है (क्योंकि वह झूठी वापसी करेगा)। यह low > (high > low)
हो सकता है लेकिन यह ऑपरेटर प्राथमिकता (आमतौर पर बाएं से दाएं) के मामले में समझ में नहीं आता है।
चेक बाहर 'functools.total_ordering' - अगर मैं सही ढंग से याद करते हैं, आप केवल एक सीएमपी जैसे' __eq__' और एक आदेश, जैसे '__lt__' आपूर्ति और' ** कक्षा में जोड़ें @ functools.total_ordering' करने की जरूरत है **, और यह आपके लिए बाकी को भरना चाहिए। – dwanderson
@ ड्वांडरसन मुझे याद है कि पाइथन आपके लिए बाकी करेगा। –