Hướng dẫn comparator in python 3 - bộ so sánh trong python 3

Hướng dẫn chuyển Python 3 bảo thủ

Python 3 là nghiêm ngặt khi so sánh các đối tượng của các loại khác nhau. Nó cũng giảm so sánh dựa trên CMP và phân loại có lợi cho các so sánh phong phú và phân loại chính, các lựa chọn thay thế hiện đại đã có sẵn ít nhất kể từ Python 2.4. Chi tiết và chiến lược chuyển tiếp theo.

Các loại không thể đặt hàng

Cách tiếp cận nghiêm ngặt để so sánh trong Python 3 khiến thường không thể so sánh các loại đối tượng khác nhau.

Ví dụ, trong Python 2, so sánh các tác phẩm intstr [với kết quả không thể đoán trước được trong các triển khai Python]:

Nhưng trong Python 3, nó thất bại với một thông báo lỗi được mô tả tốt:

>>> 2 < '2'
Traceback [most recent call last]:
File "", line 1, in 
TypeError: unorderable types: int[] < str[]

Sự thay đổi thường thể hiện trong danh sách sắp xếp: trong Python 3, danh sách với các mục thuộc loại khác nhau thường không thể sắp xếp.

Nếu bạn cần sắp xếp các danh sách không đồng nhất hoặc so sánh các loại đối tượng khác nhau, hãy thực hiện một chức năng chính để mô tả đầy đủ cách các loại khác nhau nên được đặt hàng.

So sánh phong phú

  • FIXER: Không có: None
  • Tỷ lệ lưu hành: chung

Phương pháp đặc biệt

class Person[object]:
    def __init__[self, firstname, lastname]:
         self.first = firstname
         self.last = lastname

    def __cmp__[self, other]:
        return cmp[[self.last, self.first], [other.last, other.first]]

    def __repr__[self]:
        return "%s %s" % [self.first, self.last]
0 không còn được tôn vinh trong Python 3.

Trong Python 2,

class Person[object]:
    def __init__[self, firstname, lastname]:
         self.first = firstname
         self.last = lastname

    def __cmp__[self, other]:
        return cmp[[self.last, self.first], [other.last, other.first]]

    def __repr__[self]:
        return "%s %s" % [self.first, self.last]
1 đã thực hiện so sánh giữa hai đối tượng, trả về giá trị âm nếu
class Person[object]:
    def __init__[self, firstname, lastname]:
         self.first = firstname
         self.last = lastname

    def __cmp__[self, other]:
        return cmp[[self.last, self.first], [other.last, other.first]]

    def __repr__[self]:
        return "%s %s" % [self.first, self.last]
2, dương nếu
class Person[object]:
    def __init__[self, firstname, lastname]:
         self.first = firstname
         self.last = lastname

    def __cmp__[self, other]:
        return cmp[[self.last, self.first], [other.last, other.first]]

    def __repr__[self]:
        return "%s %s" % [self.first, self.last]
3 và không nếu chúng bằng nhau.

Cách tiếp cận này thể hiện kết quả so sánh là phổ biến trong các ngôn ngữ kiểu C. Nhưng, sớm trong sự phát triển của Python 2, rõ ràng là chỉ cho phép ba trường hợp cho thứ tự tương đối của các đối tượng là quá hạn chế.

Điều này dẫn đến việc giới thiệu các phương pháp so sánh phong phú, gán một phương pháp đặc biệt cho mỗi toán tử:

Nhà điều hànhPhương pháp
==
class Person[object]:
    def __init__[self, firstname, lastname]:
         self.first = firstname
         self.last = lastname

    def __cmp__[self, other]:
        return cmp[[self.last, self.first], [other.last, other.first]]

    def __repr__[self]:
        return "%s %s" % [self.first, self.last]
4
! =
class Person[object]:
    def __init__[self, firstname, lastname]:
         self.first = firstname
         self.last = lastname

    def __cmp__[self, other]:
        return cmp[[self.last, self.first], [other.last, other.first]]

    def __repr__[self]:
        return "%s %s" % [self.first, self.last]
5
class Person[object]:
    def __init__[self, firstname, lastname]:
         self.first = firstname
         self.last = lastname

    def __cmp__[self, other]:
        return cmp[[self.last, self.first], [other.last, other.first]]

    def __repr__[self]:
        return "%s %s" % [self.first, self.last]
8
> =
class Person[object]:
    def __init__[self, firstname, lastname]:
         self.first = firstname
         self.last = lastname

    def __cmp__[self, other]:
        return cmp[[self.last, self.first], [other.last, other.first]]

    def __repr__[self]:
        return "%s %s" % [self.first, self.last]
9

Mỗi đối số lấy hai đối số giống như CMP và phải trả về giá trị kết quả [thường là boolean], tăng một ngoại lệ hoặc trả về

from functools import total_ordering

@total_ordering
class Person[object]:

    def __init__[self, firstname, lastname]:
        self.first = firstname
        self.last = lastname

    def __eq__[self, other]:
        return [[self.last, self.first] == [other.last, other.first]]

    def __ne__[self, other]:
        return not [self == other]

    def __lt__[self, other]:
        return [[self.last, self.first]  y] - [x >> actors = [Person['Eric', 'Idle'],
...           Person['John', 'Cleese'],
...           Person['Michael', 'Palin'],
...           Person['Terry', 'Gilliam'],
...           Person['Terry', 'Jones']]
...

Cách tiếp cận này thể hiện kết quả so sánh là phổ biến trong các ngôn ngữ kiểu C. Nhưng, sớm trong sự phát triển của Python 2, rõ ràng là chỉ cho phép ba trường hợp cho thứ tự tương đối của các đối tượng là quá hạn chế.

>>> def cmp_last_name[a, b]:
...     """ Compare names by last name"""
...     return cmp[a.last, b.last]
...
>>> sorted[actors, cmp=cmp_last_name]
['John Cleese', 'Terry Gilliam', 'Eric Idle', 'Terry Jones', 'Michael Palin']

Điều này dẫn đến việc giới thiệu các phương pháp so sánh phong phú, gán một phương pháp đặc biệt cho mỗi toán tử:

Nhà điều hành

>>> def keyfunction[item]:
...     """Key for comparison by last name"""
...     return item.last
...
>>> sorted[actors, key=keyfunction]
['John Cleese', 'Terry Gilliam', 'Eric Idle', 'Terry Jones', 'Michael Palin']

Phương pháp

Trong Python 3, tham số

class Person[object]:

    def __init__[self, firstname, lastname]:
        self.first = firstname
        self.last = lastname

    def __eq__[self, other]:
        return [[self.last, self.first] == [other.last, other.first]]

    def __ne__[self, other]:
        return [[self.last, self.first] != [other.last, other.first]]

    def __lt__[self, other]:
        return [[self.last, self.first] = [other.last, other.first]]

    def __repr__[self]:
        return "%s %s" % [self.first, self.last]
1 đã được xóa và chỉ có thể sử dụng
class Person[object]:

    def __init__[self, firstname, lastname]:
        self.first = firstname
        self.last = lastname

    def __eq__[self, other]:
        return [[self.last, self.first] == [other.last, other.first]]

    def __ne__[self, other]:
        return [[self.last, self.first] != [other.last, other.first]]

    def __lt__[self, other]:
        return [[self.last, self.first] = [other.last, other.first]]

    def __repr__[self]:
        return "%s %s" % [self.first, self.last]
8 [hoặc không có đối số nào].

Không có người sửa lỗi cho sự thay đổi này.Tuy nhiên, việc phát hiện ra nó rất đơn giản: cuộc gọi

def cmp[x, y]:
    """
    Replacement for built-in function cmp that was removed in Python 3

    Compare the two objects x and y and return an integer according to
    the outcome. The return value is negative if x < y, zero if x == y
    and strictly positive if x > y.
    """

    return [x > y] - [x  y] - [x  y] - [x  y] - [x  y] - [x 

Bài Viết Liên Quan

Chủ Đề