Python cho phép các biểu thức như x > y > z
, theo tài liệu, tương đương với (x > y) and (y > z)
ngoại trừ y
chỉ được đánh giá một lần. (https://docs.python.org/3/reference/expressions.html)So sánh chuỗi tùy chỉnh
Tuy nhiên, điều này dường như bị hỏng nếu tôi tùy chỉnh các hàm so sánh. Ví dụ. giả sử tôi có các lớp sau: (. Xin lỗi cho khối lớn, nhưng một khi bạn đọc các phương pháp __eq__
, phần còn lại là tầm thường)
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)
Bây giờ tôi có thể làm công cụ thú vị như CompareList([10, 5]) > CompareList([5, 10])
và nó sẽ chính xác trở CompareList([True,False])
Tuy nhiên, dí các hoạt động này không hoạt động độc đáo:
low = CompareList([1])
high = CompareList([2])
print(low > high > low) # returns CompareList([True])
Tại sao không? Điều gì xảy ra dưới mui xe ở đây? Tôi biết nó không tương đương với (low > high) > low
= (False > low)
(vì điều đó sẽ trả về Sai). Nó có thể là low > (high > low)
nhưng điều đó sẽ không có ý nghĩa về mặt ưu tiên của toán tử (thường là từ trái qua phải).
Kiểm tra 'functools.total_ordering' - nếu tôi nhớ chính xác, bạn chỉ cần cung cấp một cmp ví dụ' __eq__' và một thứ tự, ví dụ '__lt__' và thêm' @ functools.total_ordering' vào lớp ** **, và nó sẽ điền vào phần còn lại cho bạn. – dwanderson
@dwanderson Tôi nhớ đọc Python sẽ làm phần còn lại cho bạn. –