Hướng dẫn python inherit from built-in type - python kế thừa từ kiểu dựng sẵn

Tôi muốn thêm một số thuộc tính vào loại

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp, vì vậy tôi đã viết điều này:

Show
class MyList(list):
    def __new__(cls, *args, **kwargs):
        obj = super(MyList, cls).__new__(cls, *args, **kwargs)
        obj.append('FirstMen')
        return obj

    def __init__(self, *args, **kwargs):
        self.name = 'Westeros'

    def king(self):
        print 'IronThrone'

if __name__ == '__main__':
    my_list = MyList([1, 2, 3, 4])
    print my_list

nhưng

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
6 chỉ chứa phần tử
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
7. Tại sao
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
8 của tôi không hoạt động ở đây? Và làm thế nào tôi nên thừa hưởng từ một loại tích hợp như
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5? Nó có giống với các loại bất biến như
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
0 không?

hỏi ngày 24 tháng 2 năm 2012 lúc 14:50Feb 24, 2012 at 14:50

Hướng dẫn python inherit from built-in type - python kế thừa từ kiểu dựng sẵn

2

Loại

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 thường thực hiện khởi tạo thực tế của danh sách bên trong phương thức
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
2 của nó, vì nó là quy ước cho các loại có thể thay đổi. Bạn chỉ cần ghi đè lên
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
3 khi phân nhóm các loại bất biến. Mặc dù bạn có thể ghi đè lên danh sách phân lớp, nhưng không có nhiều điểm để làm như vậy cho trường hợp sử dụng của bạn. Chỉ dễ dàng hơn để ghi đè lên
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
2:

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'

Cũng lưu ý rằng tôi khuyên bạn nên sử dụng

# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
6 trong trường hợp này. Bạn muốn gọi
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
7 ở đây, và không thể có gì khác.

Đã trả lời ngày 24 tháng 2 năm 2012 lúc 14:58Feb 24, 2012 at 14:58

Sven Marnachsven MarnachSven Marnach

550K114 Huy hiệu vàng920 Huy hiệu bạc822 Huy hiệu Đồng114 gold badges920 silver badges822 bronze badges

5

Trước hết, bạn đang làm điều này như một bài tập để hiểu

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
8? Nếu không, gần như chắc chắn có một cách tốt hơn để làm những gì bạn đang cố gắng làm. Bạn có thể giải thích những gì bạn muốn đạt được ở đây?

Điều đó nói rằng, đây là những gì đang xảy ra trong ví dụ của bạn:

  1. Bạn gọi
    # string_list.py
    
    class StringList(list):
        def __init__(self, iterable):
            super().__init__(str(item) for item in iterable)
    
        def __setitem__(self, index, item):
            super().__setitem__(index, str(item))
    
        def insert(self, index, item):
            super().insert(index, str(item))
    
        def append(self, item):
            super().append(str(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                super().extend(other)
            else:
                super().extend(str(item) for item in other)
    
    9
  2. Điều này đầu tiên gọi
    >>> from string_list import StringList
    
    >>> data = StringList([1, 2, 2, 4, 5])
    >>> data
    ['1', '2', '2', '4', '5']
    
    >>> data.append(6)
    >>> data
    ['1', '2', '2', '4', '5', '6']
    
    >>> data.insert(0, 0)
    >>> data
    ['0', '1', '2', '2', '4', '5', '6']
    
    >>> data.extend([7, 8, 9])
    >>> data
    ['0', '1', '2', '2', '4', '5', '6', '7', '8', '9']
    
    >>> data[3] = 3
    >>> data
    ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    
    0
  3. Việc triển khai của bạn gọi
    >>> from string_list import StringList
    
    >>> data = StringList([1, 2, 2, 4, 5])
    >>> data
    ['1', '2', '2', '4', '5']
    
    >>> data.append(6)
    >>> data
    ['1', '2', '2', '4', '5', '6']
    
    >>> data.insert(0, 0)
    >>> data
    ['0', '1', '2', '2', '4', '5', '6']
    
    >>> data.extend([7, 8, 9])
    >>> data
    ['0', '1', '2', '2', '4', '5', '6', '7', '8', '9']
    
    >>> data[3] = 3
    >>> data
    ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    
    1 Điều này trả về một phiên bản mới là
    >>> from string_list import StringList
    
    >>> data = StringList([1, 2, 2, 4, 5])
    >>> data
    ['1', '2', '2', '4', '5']
    
    >>> data.append(6)
    >>> data
    ['1', '2', '2', '4', '5', '6']
    
    >>> data.insert(0, 0)
    >>> data
    ['0', '1', '2', '2', '4', '5', '6']
    
    >>> data.extend([7, 8, 9])
    >>> data
    ['0', '1', '2', '2', '4', '5', '6', '7', '8', '9']
    
    >>> data[3] = 3
    >>> data
    ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    
    2, không có yếu tố.
    >>> from string_list import StringList
    
    >>> data = StringList([1, 2, 2, 4, 5])
    >>> data
    ['1', '2', '2', '4', '5']
    
    >>> data.append(6)
    >>> data
    ['1', '2', '2', '4', '5', '6']
    
    >>> data.insert(0, 0)
    >>> data
    ['0', '1', '2', '2', '4', '5', '6']
    
    >>> data.extend([7, 8, 9])
    >>> data
    ['0', '1', '2', '2', '4', '5', '6', '7', '8', '9']
    
    >>> data[3] = 3
    >>> data
    ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    
    3 không điền vào danh sách. Nó để lại điều đó đến
    >>> from string_list import StringList
    
    >>> data = StringList([1, 2, 2, 4, 5])
    >>> data
    ['1', '2', '2', '4', '5']
    
    >>> data.append(6)
    >>> data
    ['1', '2', '2', '4', '5', '6']
    
    >>> data.insert(0, 0)
    >>> data
    ['0', '1', '2', '2', '4', '5', '6']
    
    >>> data.extend([7, 8, 9])
    >>> data
    ['0', '1', '2', '2', '4', '5', '6', '7', '8', '9']
    
    >>> data[3] = 3
    >>> data
    ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    
    4, mà không bao giờ được gọi.
  4. Phương thức
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    8 của bạn bổ sung
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    7 vào ví dụ
    >>> from string_list import StringList
    
    >>> data = StringList([1, 2, 2, 4, 5])
    >>> data
    ['1', '2', '2', '4', '5']
    
    >>> data.append(6)
    >>> data
    ['1', '2', '2', '4', '5', '6']
    
    >>> data.insert(0, 0)
    >>> data
    ['0', '1', '2', '2', '4', '5', '6']
    
    >>> data.extend([7, 8, 9])
    >>> data
    ['0', '1', '2', '2', '4', '5', '6', '7', '8', '9']
    
    >>> data[3] = 3
    >>> data
    ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    
    2 trống.
  5. Phương thức
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    8 của bạn trả về thể hiện của
    >>> from string_list import StringList
    
    >>> data = StringList([1, 2, 2, 4, 5])
    >>> data
    ['1', '2', '2', '4', '5']
    
    >>> data.append(6)
    >>> data
    ['1', '2', '2', '4', '5', '6']
    
    >>> data.insert(0, 0)
    >>> data
    ['0', '1', '2', '2', '4', '5', '6']
    
    >>> data.extend([7, 8, 9])
    >>> data
    ['0', '1', '2', '2', '4', '5', '6', '7', '8', '9']
    
    >>> data[3] = 3
    >>> data
    ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    
    2.
  6. # string_list.py
    
    from collections import UserList
    
    class StringList(UserList):
        def __init__(self, iterable):
            super().__init__(str(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = str(item)
    
        def insert(self, index, item):
            self.data.insert(index, str(item))
    
        def append(self, item):
            self.data.append(str(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(str(item) for item in other)
    
    0 được gọi.
  7. Nó đặt thuộc tính
    # string_list.py
    
    from collections import UserList
    
    class StringList(UserList):
        def __init__(self, iterable):
            super().__init__(str(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = str(item)
    
        def insert(self, index, item):
            self.data.insert(index, str(item))
    
        def append(self, item):
            self.data.append(str(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(str(item) for item in other)
    
    1 thành
    # string_list.py
    
    from collections import UserList
    
    class StringList(UserList):
        def __init__(self, iterable):
            super().__init__(str(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = str(item)
    
        def insert(self, index, item):
            self.data.insert(index, str(item))
    
        def append(self, item):
            self.data.append(str(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(str(item) for item in other)
    
    2.
  8. Nó trở lại.
  9. Trường hợp được gán cho
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    6 và in.

Xem ở đây để biết giải thích về

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
8: http://docs.python.org/reference/datamodel.html#basic-customization

Đã trả lời ngày 24 tháng 2 năm 2012 lúc 15:08Feb 24, 2012 at 15:08

WEBELWEEBEWeeble

16,5K3 Huy hiệu vàng57 Huy hiệu bạc72 Huy hiệu đồng3 gold badges57 silver badges72 bronze badges

2

Tại một số điểm trong cuộc phiêu lưu mã hóa Python của bạn, bạn có thể cần tạo các lớp giống như danh sách tùy chỉnh với hành vi sửa đổi, chức năng mới hoặc cả hai. Để thực hiện điều này trong Python, bạn có thể kế thừa từ một lớp cơ sở trừu tượng, trực tiếp đến lớp

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp hoặc kế thừa từ
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6, sống trong mô-đun
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
7.custom list-like classes with modified behavior, new functionalities, or both. To do this in Python, you can inherit from an abstract base class, subclass the built-in
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 class directly, or inherit from
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6, which lives in the
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
7 module.

Trong hướng dẫn này, bạn sẽ học cách:

  • Tạo các lớp giống như danh sách tùy chỉnh bằng cách kế thừa từ lớp
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    5 tích hợpbuilt-in
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    5 class
  • Xây dựng các lớp giống như danh sách tùy chỉnh bằng cách phân lớp
    # string_list.py
    
    from collections import UserList
    
    class StringList(UserList):
        def __init__(self, iterable):
            super().__init__(str(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = str(item)
    
        def insert(self, index, item):
            self.data.insert(index, str(item))
    
        def append(self, item):
            self.data.append(str(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(str(item) for item in other)
    
    6 từ mô-đun
    # string_list.py
    
    from collections import UserList
    
    class StringList(UserList):
        def __init__(self, iterable):
            super().__init__(str(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = str(item)
    
        def insert(self, index, item):
            self.data.insert(index, str(item))
    
        def append(self, item):
            self.data.append(str(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(str(item) for item in other)
    
    7
    # string_list.py
    
    from collections import UserList
    
    class StringList(UserList):
        def __init__(self, iterable):
            super().__init__(str(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = str(item)
    
        def insert(self, index, item):
            self.data.insert(index, str(item))
    
        def append(self, item):
            self.data.append(str(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(str(item) for item in other)
    
    6
    from the
    # string_list.py
    
    from collections import UserList
    
    class StringList(UserList):
        def __init__(self, iterable):
            super().__init__(str(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = str(item)
    
        def insert(self, index, item):
            self.data.insert(index, str(item))
    
        def append(self, item):
            self.data.append(str(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(str(item) for item in other)
    
    7 module

Bạn cũng sẽ viết một số ví dụ về việc mà bạn sẽ giúp bạn quyết định lớp cha,

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 hoặc
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6, để sử dụng khi tạo các lớp danh sách tùy chỉnh của bạn.

Để tận dụng tối đa hướng dẫn này, bạn nên quen thuộc với lớp

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp của Python và các tính năng tiêu chuẩn của nó. Bạn cũng cần biết những điều cơ bản của lập trình hướng đối tượng và hiểu cách thức kế thừa hoạt động trong Python.

Tạo các lớp giống như danh sách trong Python

Lớp

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp là một loại dữ liệu cơ bản trong Python. Danh sách này rất hữu ích trong nhiều tình huống và có hàng tấn trường hợp sử dụng thực tế. Trong một số trường hợp sử dụng này, chức năng tiêu chuẩn của Python
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 có thể không đủ và bạn có thể cần phải tạo các lớp giống như danh sách tùy chỉnh để giải quyết vấn đề trong tay.

Bạn thường tìm thấy ít nhất hai lý do để tạo các lớp giống như danh sách tùy chỉnh:

  1. Mở rộng danh sách thông thường bằng cách thêm chức năng mới the regular list by adding new functionality
  2. Sửa đổi chức năng danh sách tiêu chuẩn the standard list’s functionality

Bạn cũng có thể đối mặt với các tình huống mà bạn cần để mở rộng và sửa đổi chức năng tiêu chuẩn của danh sách.

Tùy thuộc vào nhu cầu cụ thể và cấp độ kỹ năng của bạn, bạn có thể sử dụng một vài chiến lược để tạo các lớp giống như danh sách tùy chỉnh của riêng bạn. Bạn có thể:

  • Kế thừa từ một lớp cơ sở trừu tượng thích hợp, chẳng hạn như
    >>> from string_list import StringList
    
    >>> data = StringList([1, 2, 2, 4, 5])
    >>> data
    ['1', '2', '2', '4', '5']
    
    >>> data.append(6)
    >>> data
    ['1', '2', '2', '4', '5', '6']
    
    >>> data.insert(0, 0)
    >>> data
    ['0', '1', '2', '2', '4', '5', '6']
    
    >>> data.extend([7, 8, 9])
    >>> data
    ['0', '1', '2', '2', '4', '5', '6', '7', '8', '9']
    
    >>> data[3] = 3
    >>> data
    ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    
    6
  • Kế thừa từ lớp Python tích hợp trực tiếp
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    5
  • Lớp con
    # string_list.py
    
    from collections import UserList
    
    class StringList(UserList):
        def __init__(self, iterable):
            super().__init__(str(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = str(item)
    
        def insert(self, index, item):
            self.data.insert(index, str(item))
    
        def append(self, item):
            self.data.append(str(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(str(item) for item in other)
    
    6 từ
    # string_list.py
    
    from collections import UserList
    
    class StringList(UserList):
        def __init__(self, iterable):
            super().__init__(str(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = str(item)
    
        def insert(self, index, item):
            self.data.insert(index, str(item))
    
        def append(self, item):
            self.data.append(str(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(str(item) for item in other)
    
    7

Có một vài cân nhắc khi bạn chọn chiến lược thích hợp để sử dụng. Hãy đọc để biết thêm chi tiết.

Xây dựng một lớp giống như danh sách từ một lớp cơ sở trừu tượng

Bạn có thể tạo các lớp giống như danh sách của riêng mình bằng cách kế thừa từ một lớp cơ sở trừu tượng thích hợp (ABC), như

>>> from string_list import StringList

>>> data = StringList([1, 2, 2, 4, 5])
>>> data
['1', '2', '2', '4', '5']

>>> data.append(6)
>>> data
['1', '2', '2', '4', '5', '6']

>>> data.insert(0, 0)
>>> data
['0', '1', '2', '2', '4', '5', '6']

>>> data.extend([7, 8, 9])
>>> data
['0', '1', '2', '2', '4', '5', '6', '7', '8', '9']

>>> data[3] = 3
>>> data
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
6. ABC này cung cấp các triển khai chung của hầu hết các phương thức
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 ngoại trừ
# number_list.py

class NumberList(list):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, self._validate_number(item))

    def insert(self, index, item):
        super().insert(index, self._validate_number(item))

    def append(self, item):
        super().append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )
2,
# number_list.py

class NumberList(list):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, self._validate_number(item))

    def insert(self, index, item):
        super().insert(index, self._validate_number(item))

    def append(self, item):
        super().append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )
3,
# number_list.py

class NumberList(list):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, self._validate_number(item))

    def insert(self, index, item):
        super().insert(index, self._validate_number(item))

    def append(self, item):
        super().append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )
4,
# number_list.py

class NumberList(list):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, self._validate_number(item))

    def insert(self, index, item):
        super().insert(index, self._validate_number(item))

    def append(self, item):
        super().append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )
5 và
# number_list.py

class NumberList(list):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, self._validate_number(item))

    def insert(self, index, item):
        super().insert(index, self._validate_number(item))

    def append(self, item):
        super().append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )
6. Vì vậy, khi kế thừa từ lớp này, bạn sẽ phải tự mình thực hiện các phương pháp này.abstract base class (ABC), like
>>> from string_list import StringList

>>> data = StringList([1, 2, 2, 4, 5])
>>> data
['1', '2', '2', '4', '5']

>>> data.append(6)
>>> data
['1', '2', '2', '4', '5', '6']

>>> data.insert(0, 0)
>>> data
['0', '1', '2', '2', '4', '5', '6']

>>> data.extend([7, 8, 9])
>>> data
['0', '1', '2', '2', '4', '5', '6', '7', '8', '9']

>>> data[3] = 3
>>> data
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
6. This ABC provides generic implementations of most
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 methods except for
# number_list.py

class NumberList(list):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, self._validate_number(item))

    def insert(self, index, item):
        super().insert(index, self._validate_number(item))

    def append(self, item):
        super().append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )
2,
# number_list.py

class NumberList(list):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, self._validate_number(item))

    def insert(self, index, item):
        super().insert(index, self._validate_number(item))

    def append(self, item):
        super().append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )
3,
# number_list.py

class NumberList(list):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, self._validate_number(item))

    def insert(self, index, item):
        super().insert(index, self._validate_number(item))

    def append(self, item):
        super().append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )
4,
# number_list.py

class NumberList(list):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, self._validate_number(item))

    def insert(self, index, item):
        super().insert(index, self._validate_number(item))

    def append(self, item):
        super().append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )
5, and
# number_list.py

class NumberList(list):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, self._validate_number(item))

    def insert(self, index, item):
        super().insert(index, self._validate_number(item))

    def append(self, item):
        super().append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )
6. So, when inheriting from this class, you’ll have to implement these methods yourself.

Viết triển khai của riêng bạn cho tất cả các phương pháp đặc biệt này là một lượng công việc hợp lý. Nó dễ bị lỗi và yêu cầu kiến ​​thức nâng cao về Python và mô hình dữ liệu của nó. Nó cũng có thể ngụ ý các vấn đề về hiệu suất bởi vì bạn sẽ viết các phương thức trong Python thuần túy.

Ngoài ra, giả sử bạn cần tùy chỉnh chức năng của bất kỳ phương thức danh sách tiêu chuẩn nào khác, như

# number_list.py

class NumberList(list):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, self._validate_number(item))

    def insert(self, index, item):
        super().insert(index, self._validate_number(item))

    def append(self, item):
        super().append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )
7 hoặc
# number_list.py

class NumberList(list):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, self._validate_number(item))

    def insert(self, index, item):
        super().insert(index, self._validate_number(item))

    def append(self, item):
        super().append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )
6. Trong trường hợp đó, bạn sẽ phải ghi đè triển khai mặc định và cung cấp một triển khai phù hợp đáp ứng nhu cầu của bạn.

Ưu điểm chính của chiến lược này để tạo các lớp giống như danh sách là lớp ABC cha mẹ sẽ cảnh báo bạn nếu bạn bỏ lỡ bất kỳ phương thức cần thiết nào trong triển khai tùy chỉnh của bạn.

Nói chung, bạn chỉ nên nắm lấy chiến lược này nếu bạn cần một lớp giống như danh sách mà khác về cơ bản so với lớp

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp.

Trong hướng dẫn này, bạn sẽ tập trung vào việc tạo các lớp giống như danh sách bằng cách kế thừa từ lớp

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp và lớp
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 từ mô-đun thư viện tiêu chuẩn
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
7. Những chiến lược này dường như là những chiến lược nhanh nhất và thực tế nhất.

Kế thừa từ lớp Python, tích hợp class MyList(list): def __init__(self, *args): list.__init__(self, *args) self.append('FirstMen') self.name = 'Westeros' 5

Trong một thời gian dài, không thể kế thừa trực tiếp từ các loại Python được thực hiện trong C. Python 2.2 đã khắc phục vấn đề này. Bây giờ bạn có thể phân lớp các loại tích hợp, bao gồm

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5. Thay đổi này đã mang lại một số lợi thế kỹ thuật cho các lớp con vì bây giờ họ:

  • Sẽ hoạt động ở mọi nơi yêu cầu loại tích hợp ban đầu
  • Có thể xác định các phương thức phiên bản mới, tĩnh và lớp
  • Có thể lưu trữ các thuộc tính thể hiện của chúng trong thuộc tính lớp
    >>> from number_list import NumberList
    
    >>> numbers = NumberList([1.1, 2, 3j])
    >>> numbers
    [1.1, 2, 3j]
    
    >>> numbers.append("4.2")
    Traceback (most recent call last):
        ...
    TypeError: numeric value expected, got str
    
    >>> numbers.append(4.2)
    >>> numbers
    [1.1, 2, 3j, 4.2]
    
    >>> numbers.insert(0, "0")
    Traceback (most recent call last):
        ...
    TypeError: numeric value expected, got str
    
    >>> numbers.insert(0, 0)
    >>> numbers
    [0, 1.1, 2, 3j, 4.2]
    
    >>> numbers.extend(["5.3", "6"])
    Traceback (most recent call last):
        ...
    TypeError: numeric value expected, got str
    
    >>> numbers.extend([5.3, 6])
    >>> numbers
    [0, 1.1, 2, 3j, 4.2, 5.3, 6]
    
    5, về cơ bản thay thế thuộc tính
    >>> from number_list import NumberList
    
    >>> numbers = NumberList([1.1, 2, 3j])
    >>> numbers
    [1.1, 2, 3j]
    
    >>> numbers.append("4.2")
    Traceback (most recent call last):
        ...
    TypeError: numeric value expected, got str
    
    >>> numbers.append(4.2)
    >>> numbers
    [1.1, 2, 3j, 4.2]
    
    >>> numbers.insert(0, "0")
    Traceback (most recent call last):
        ...
    TypeError: numeric value expected, got str
    
    >>> numbers.insert(0, 0)
    >>> numbers
    [0, 1.1, 2, 3j, 4.2]
    
    >>> numbers.extend(["5.3", "6"])
    Traceback (most recent call last):
        ...
    TypeError: numeric value expected, got str
    
    >>> numbers.extend([5.3, 6])
    >>> numbers
    [0, 1.1, 2, 3j, 4.2, 5.3, 6]
    
    6

Mục đầu tiên trong danh sách này có thể là một yêu cầu đối với mã C mong đợi một lớp tích hợp Python. Mục thứ hai cho phép bạn thêm chức năng mới trên hành vi danh sách tiêu chuẩn. Cuối cùng, mục thứ ba sẽ cho phép bạn hạn chế các thuộc tính của một lớp con chỉ có các thuộc tính được xác định trước trong

>>> from number_list import NumberList

>>> numbers = NumberList([1.1, 2, 3j])
>>> numbers
[1.1, 2, 3j]

>>> numbers.append("4.2")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.append(4.2)
>>> numbers
[1.1, 2, 3j, 4.2]

>>> numbers.insert(0, "0")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.insert(0, 0)
>>> numbers
[0, 1.1, 2, 3j, 4.2]

>>> numbers.extend(["5.3", "6"])
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.extend([5.3, 6])
>>> numbers
[0, 1.1, 2, 3j, 4.2, 5.3, 6]
5.

Để khởi động mọi thứ và bắt đầu tạo các lớp giống như danh sách tùy chỉnh, giả sử rằng bạn cần một danh sách tự động lưu trữ tất cả các mục của nó dưới dạng chuỗi. Giả sử rằng danh sách tùy chỉnh của bạn sẽ chỉ lưu trữ các số làm chuỗi, bạn có thể tạo lớp con sau của

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5:

# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)

Các lớp con

>>> from number_list import NumberList

>>> numbers = NumberList([1.1, 2, 3j])
>>> numbers
[1.1, 2, 3j]

>>> numbers.append("4.2")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.append(4.2)
>>> numbers
[1.1, 2, 3j, 4.2]

>>> numbers.insert(0, "0")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.insert(0, 0)
>>> numbers
[0, 1.1, 2, 3j, 4.2]

>>> numbers.extend(["5.3", "6"])
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.extend([5.3, 6])
>>> numbers
[0, 1.1, 2, 3j, 4.2, 5.3, 6]
9 của bạn trực tiếp
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5, điều đó có nghĩa là nó sẽ kế thừa tất cả các chức năng của Python
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tiêu chuẩn. Vì bạn muốn danh sách của mình lưu trữ các mục dưới dạng chuỗi, bạn cần sửa đổi tất cả các phương thức thêm hoặc sửa đổi các mục trong danh sách cơ bản. Những phương pháp đó bao gồm những điều sau:

  • # number_list.py
    
    from collections import UserList
    
    class NumberList(UserList):
        def __init__(self, iterable):
            super().__init__(self._validate_number(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = self._validate_number(item)
    
        def insert(self, index, item):
            self.data.insert(index, self._validate_number(item))
    
        def append(self, item):
            self.data.append(self._validate_number(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(self._validate_number(item) for item in other)
    
        def _validate_number(self, value):
            if isinstance(value, (int, float, complex)):
                return value
            raise TypeError(
                f"numeric value expected, got {type(value).__name__}"
            )
    
    2 Khởi tạo tất cả các phiên bản mới của lớp.
    initializes all the class’s new instances.
  • # number_list.py
    
    class NumberList(list):
        def __init__(self, iterable):
            super().__init__(self._validate_number(item) for item in iterable)
    
        def __setitem__(self, index, item):
            super().__setitem__(index, self._validate_number(item))
    
        def insert(self, index, item):
            super().insert(index, self._validate_number(item))
    
        def append(self, item):
            super().append(self._validate_number(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                super().extend(other)
            else:
                super().extend(self._validate_number(item) for item in other)
    
        def _validate_number(self, value):
            if isinstance(value, (int, float, complex)):
                return value
            raise TypeError(
                f"numeric value expected, got {type(value).__name__}"
            )
    
    3 cho phép bạn gán một giá trị mới cho một mục hiện tại bằng cách sử dụng chỉ mục của mục, như trong
    # number_list.py
    
    from collections import UserList
    
    class NumberList(UserList):
        def __init__(self, iterable):
            super().__init__(self._validate_number(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = self._validate_number(item)
    
        def insert(self, index, item):
            self.data.insert(index, self._validate_number(item))
    
        def append(self, item):
            self.data.append(self._validate_number(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(self._validate_number(item) for item in other)
    
        def _validate_number(self, value):
            if isinstance(value, (int, float, complex)):
                return value
            raise TypeError(
                f"numeric value expected, got {type(value).__name__}"
            )
    
    4.
    allows you to assign a new value to an existing item using the item’s index, like in
    # number_list.py
    
    from collections import UserList
    
    class NumberList(UserList):
        def __init__(self, iterable):
            super().__init__(self._validate_number(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = self._validate_number(item)
    
        def insert(self, index, item):
            self.data.insert(index, self._validate_number(item))
    
        def append(self, item):
            self.data.append(self._validate_number(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(self._validate_number(item) for item in other)
    
        def _validate_number(self, value):
            if isinstance(value, (int, float, complex)):
                return value
            raise TypeError(
                f"numeric value expected, got {type(value).__name__}"
            )
    
    4.
  • # number_list.py
    
    class NumberList(list):
        def __init__(self, iterable):
            super().__init__(self._validate_number(item) for item in iterable)
    
        def __setitem__(self, index, item):
            super().__setitem__(index, self._validate_number(item))
    
        def insert(self, index, item):
            super().insert(index, self._validate_number(item))
    
        def append(self, item):
            super().append(self._validate_number(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                super().extend(other)
            else:
                super().extend(self._validate_number(item) for item in other)
    
        def _validate_number(self, value):
            if isinstance(value, (int, float, complex)):
                return value
            raise TypeError(
                f"numeric value expected, got {type(value).__name__}"
            )
    
    6 cho phép bạn chèn một mục mới tại một vị trí nhất định trong danh sách cơ bản bằng cách sử dụng chỉ mục vật phẩm.
    allows you to insert a new item at a given position in the underlying list using the item’s index.
  • # number_list.py
    
    class NumberList(list):
        def __init__(self, iterable):
            super().__init__(self._validate_number(item) for item in iterable)
    
        def __setitem__(self, index, item):
            super().__setitem__(index, self._validate_number(item))
    
        def insert(self, index, item):
            super().insert(index, self._validate_number(item))
    
        def append(self, item):
            super().append(self._validate_number(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                super().extend(other)
            else:
                super().extend(self._validate_number(item) for item in other)
    
        def _validate_number(self, value):
            if isinstance(value, (int, float, complex)):
                return value
            raise TypeError(
                f"numeric value expected, got {type(value).__name__}"
            )
    
    7 thêm một mục mới duy nhất ở cuối danh sách cơ bản.
    adds a single new item at the end of the underlying list.
  • # number_list.py
    
    from collections import UserList
    
    class NumberList(UserList):
        def __init__(self, iterable):
            super().__init__(self._validate_number(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = self._validate_number(item)
    
        def insert(self, index, item):
            self.data.insert(index, self._validate_number(item))
    
        def append(self, item):
            self.data.append(self._validate_number(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(self._validate_number(item) for item in other)
    
        def _validate_number(self, value):
            if isinstance(value, (int, float, complex)):
                return value
            raise TypeError(
                f"numeric value expected, got {type(value).__name__}"
            )
    
    7 thêm một loạt các mục vào cuối danh sách.
    adds a series of items to the end of the list.

Các phương pháp khác mà lớp

>>> from number_list import NumberList

>>> numbers = NumberList([1.1, 2, 3j])
>>> numbers
[1.1, 2, 3j]

>>> numbers.append("4.2")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.append(4.2)
>>> numbers
[1.1, 2, 3j, 4.2]

>>> numbers.insert(0, "0")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.insert(0, 0)
>>> numbers
[0, 1.1, 2, 3j, 4.2]

>>> numbers.extend(["5.3", "6"])
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.extend([5.3, 6])
>>> numbers
[0, 1.1, 2, 3j, 4.2, 5.3, 6]
9 của bạn được kế thừa từ
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 hoạt động tốt vì họ không thêm hoặc cập nhật các mục trong danh sách tùy chỉnh của bạn.

Để sử dụng

>>> from number_list import NumberList

>>> numbers = NumberList([1.1, 2, 3j])
>>> numbers
[1.1, 2, 3j]

>>> numbers.append("4.2")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.append(4.2)
>>> numbers
[1.1, 2, 3j, 4.2]

>>> numbers.insert(0, "0")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.insert(0, 0)
>>> numbers
[0, 1.1, 2, 3j, 4.2]

>>> numbers.extend(["5.3", "6"])
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.extend([5.3, 6])
>>> numbers
[0, 1.1, 2, 3j, 4.2, 5.3, 6]
9 trong mã của bạn, bạn có thể làm điều gì đó như sau:

>>>

>>> from string_list import StringList

>>> data = StringList([1, 2, 2, 4, 5])
>>> data
['1', '2', '2', '4', '5']

>>> data.append(6)
>>> data
['1', '2', '2', '4', '5', '6']

>>> data.insert(0, 0)
>>> data
['0', '1', '2', '2', '4', '5', '6']

>>> data.extend([7, 8, 9])
>>> data
['0', '1', '2', '2', '4', '5', '6', '7', '8', '9']

>>> data[3] = 3
>>> data
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

Lớp học của bạn hoạt động như mong đợi. Nó chuyển đổi tất cả các giá trị đầu vào thành các chuỗi khi đang bay. Điều đó thật tuyệt, phải không? Khi bạn tạo một thể hiện mới của

>>> from number_list import NumberList

>>> numbers = NumberList([1.1, 2, 3j])
>>> numbers
[1.1, 2, 3j]

>>> numbers.append("4.2")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.append(4.2)
>>> numbers
[1.1, 2, 3j, 4.2]

>>> numbers.insert(0, "0")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.insert(0, 0)
>>> numbers
[0, 1.1, 2, 3j, 4.2]

>>> numbers.extend(["5.3", "6"])
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.extend([5.3, 6])
>>> numbers
[0, 1.1, 2, 3j, 4.2, 5.3, 6]
9, trình khởi tạo lớp học sẽ chăm sóc chuyển đổi.

Khi bạn nối, chèn, mở rộng hoặc gán các giá trị mới cho các phiên bản lớp, các phương thức hỗ trợ mỗi thao tác sẽ chăm sóc quy trình chuyển đổi chuỗi. Bằng cách này, danh sách của bạn sẽ luôn lưu trữ các mục của nó dưới dạng các đối tượng chuỗi.

Phân lớp # string_list.py from collections import UserList class StringList(UserList): def __init__(self, iterable): super().__init__(str(item) for item in iterable) def __setitem__(self, index, item): self.data[index] = str(item) def insert(self, index, item): self.data.insert(index, str(item)) def append(self, item): self.data.append(str(item)) def extend(self, other): if isinstance(other, type(self)): self.data.extend(other) else: self.data.extend(str(item) for item in other) 6 từ # string_list.py from collections import UserList class StringList(UserList): def __init__(self, iterable): super().__init__(str(item) for item in iterable) def __setitem__(self, index, item): self.data[index] = str(item) def insert(self, index, item): self.data.insert(index, str(item)) def append(self, item): self.data.append(str(item)) def extend(self, other): if isinstance(other, type(self)): self.data.extend(other) else: self.data.extend(str(item) for item in other) 7

Một cách khác để tạo một lớp giống như danh sách tùy chỉnh là sử dụng lớp

# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 từ mô-đun
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
7. Lớp này là một trình bao bọc xung quanh loại
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp. Nó được thiết kế để tạo lại các đối tượng giống như danh sách khi nó không thể kế thừa trực tiếp từ lớp
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp.

Mặc dù sự cần thiết của lớp này đã được thay thế một phần bởi khả năng phân lớp trực tiếp lớp

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp,
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 vẫn có sẵn trong thư viện tiêu chuẩn, cả để thuận tiện và khả năng tương thích ngược.

Tính năng phân biệt của

# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 là nó cho phép bạn truy cập vào thuộc tính ____101 của nó, có thể tạo điều kiện cho việc tạo danh sách tùy chỉnh của bạn vì bạn không cần sử dụng
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
6 mọi lúc. Thuộc tính ____101 giữ một Python
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 thông thường, trống theo mặc định.

Tại đây, cách thức bạn có thể thực hiện lại lớp

>>> from number_list import NumberList

>>> numbers = NumberList([1.1, 2, 3j])
>>> numbers
[1.1, 2, 3j]

>>> numbers.append("4.2")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.append(4.2)
>>> numbers
[1.1, 2, 3j, 4.2]

>>> numbers.insert(0, "0")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.insert(0, 0)
>>> numbers
[0, 1.1, 2, 3j, 4.2]

>>> numbers.extend(["5.3", "6"])
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.extend([5.3, 6])
>>> numbers
[0, 1.1, 2, 3j, 4.2, 5.3, 6]
9 của mình bằng cách kế thừa từ
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6:

# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)

Trong ví dụ này, có quyền truy cập vào thuộc tính

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
01 cho phép bạn mã hóa lớp theo cách đơn giản hơn bằng cách sử dụng ủy quyền, điều đó có nghĩa là danh sách trong
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
01 đảm nhận việc xử lý tất cả các yêu cầu.

Bây giờ bạn gần như không phải sử dụng các công cụ nâng cao như

# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
6. Bạn chỉ cần gọi chức năng này trong trình khởi tạo lớp để ngăn chặn các vấn đề trong các kịch bản kế thừa hơn nữa. Trong phần còn lại của các phương pháp, bạn chỉ cần tận dụng
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
01, nắm giữ danh sách Python thông thường. Làm việc với danh sách là một kỹ năng mà bạn có thể đã có.

Phiên bản mới này hoạt động giống như phiên bản đầu tiên của bạn là

>>> from number_list import NumberList

>>> numbers = NumberList([1.1, 2, 3j])
>>> numbers
[1.1, 2, 3j]

>>> numbers.append("4.2")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.append(4.2)
>>> numbers
[1.1, 2, 3j, 4.2]

>>> numbers.insert(0, "0")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.insert(0, 0)
>>> numbers
[0, 1.1, 2, 3j, 4.2]

>>> numbers.extend(["5.3", "6"])
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.extend([5.3, 6])
>>> numbers
[0, 1.1, 2, 3j, 4.2, 5.3, 6]
9. Hãy tiếp tục và chạy mã sau để dùng thử:

>>>

>>> from string_list import StringList

>>> data = StringList([1, 2, 2, 4, 5])
>>> data
['1', '2', '2', '4', '5']

>>> data.append(6)
>>> data
['1', '2', '2', '4', '5', '6']

>>> data.insert(0, 0)
>>> data
['0', '1', '2', '2', '4', '5', '6']

>>> data.extend([7, 8, 9])
>>> data
['0', '1', '2', '2', '4', '5', '6', '7', '8', '9']

>>> data[3] = 3
>>> data
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

Lớp học của bạn hoạt động như mong đợi. Nó chuyển đổi tất cả các giá trị đầu vào thành các chuỗi khi đang bay. Điều đó thật tuyệt, phải không? Khi bạn tạo một thể hiện mới của

>>> from number_list import NumberList

>>> numbers = NumberList([1.1, 2, 3j])
>>> numbers
[1.1, 2, 3j]

>>> numbers.append("4.2")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.append(4.2)
>>> numbers
[1.1, 2, 3j, 4.2]

>>> numbers.insert(0, "0")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.insert(0, 0)
>>> numbers
[0, 1.1, 2, 3j, 4.2]

>>> numbers.extend(["5.3", "6"])
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.extend([5.3, 6])
>>> numbers
[0, 1.1, 2, 3j, 4.2, 5.3, 6]
9, trình khởi tạo lớp học sẽ chăm sóc chuyển đổi.

Khi bạn nối, chèn, mở rộng hoặc gán các giá trị mới cho các phiên bản lớp, các phương thức hỗ trợ mỗi thao tác sẽ chăm sóc quy trình chuyển đổi chuỗi. Bằng cách này, danh sách của bạn sẽ luôn lưu trữ các mục của nó dưới dạng các đối tượng chuỗi.

Phân lớp

# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 từ
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
7

Một cách khác để tạo một lớp giống như danh sách tùy chỉnh là sử dụng lớp

# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 từ mô-đun
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
7. Lớp này là một trình bao bọc xung quanh loại
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp. Nó được thiết kế để tạo lại các đối tượng giống như danh sách khi nó không thể kế thừa trực tiếp từ lớp
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp.

Mặc dù sự cần thiết của lớp này đã được thay thế một phần bởi khả năng phân lớp trực tiếp lớp

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp,
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 vẫn có sẵn trong thư viện tiêu chuẩn, cả để thuận tiện và khả năng tương thích ngược.

Tính năng phân biệt của

# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 là nó cho phép bạn truy cập vào thuộc tính ____101 của nó, có thể tạo điều kiện cho việc tạo danh sách tùy chỉnh của bạn vì bạn không cần sử dụng
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
6 mọi lúc. Thuộc tính ____101 giữ một Python
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 thông thường, trống theo mặc định.

Tại đây, cách thức bạn có thể thực hiện lại lớp >>> from number_list import NumberList >>> numbers = NumberList([1.1, 2, 3j]) >>> numbers [1.1, 2, 3j] >>> numbers.append("4.2") Traceback (most recent call last): ... TypeError: numeric value expected, got str >>> numbers.append(4.2) >>> numbers [1.1, 2, 3j, 4.2] >>> numbers.insert(0, "0") Traceback (most recent call last): ... TypeError: numeric value expected, got str >>> numbers.insert(0, 0) >>> numbers [0, 1.1, 2, 3j, 4.2] >>> numbers.extend(["5.3", "6"]) Traceback (most recent call last): ... TypeError: numeric value expected, got str >>> numbers.extend([5.3, 6]) >>> numbers [0, 1.1, 2, 3j, 4.2, 5.3, 6] 9 của mình bằng cách kế thừa từ # string_list.py from collections import UserList class StringList(UserList): def __init__(self, iterable): super().__init__(str(item) for item in iterable) def __setitem__(self, index, item): self.data[index] = str(item) def insert(self, index, item): self.data.insert(index, str(item)) def append(self, item): self.data.append(str(item)) def extend(self, other): if isinstance(other, type(self)): self.data.extend(other) else: self.data.extend(str(item) for item in other) 6:

Trong ví dụ này, có quyền truy cập vào thuộc tính

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
01 cho phép bạn mã hóa lớp theo cách đơn giản hơn bằng cách sử dụng ủy quyền, điều đó có nghĩa là danh sách trong
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
01 đảm nhận việc xử lý tất cả các yêu cầu.

Ở đây, một triển khai của một lớp

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
30 với chức năng mong muốn:

# number_list.py

class NumberList(list):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, self._validate_number(item))

    def insert(self, index, item):
        super().insert(index, self._validate_number(item))

    def append(self, item):
        super().append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )

Trong ví dụ này, lớp

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
30 của bạn kế thừa trực tiếp từ
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5. Điều này có nghĩa là lớp của bạn chia sẻ tất cả các chức năng cốt lõi với lớp
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp. Bạn có thể lặp lại các trường hợp
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
30, truy cập và cập nhật các mục của nó bằng các chỉ số của họ, gọi các phương thức
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 phổ biến và hơn thế nữa.

Bây giờ, để đảm bảo rằng mọi mục đầu vào là một số, bạn cần xác thực từng mục trong tất cả các phương thức hỗ trợ các hoạt động để thêm các mục mới hoặc cập nhật các mục hiện có trong danh sách. Các phương pháp cần thiết giống như trong ví dụ

>>> from number_list import NumberList

>>> numbers = NumberList([1.1, 2, 3j])
>>> numbers
[1.1, 2, 3j]

>>> numbers.append("4.2")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.append(4.2)
>>> numbers
[1.1, 2, 3j, 4.2]

>>> numbers.insert(0, "0")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.insert(0, 0)
>>> numbers
[0, 1.1, 2, 3j, 4.2]

>>> numbers.extend(["5.3", "6"])
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.extend([5.3, 6])
>>> numbers
[0, 1.1, 2, 3j, 4.2, 5.3, 6]
9 trở lại trong phần kế thừa từ phần lớp
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp của Python.

Để xác thực dữ liệu đầu vào, bạn sử dụng phương thức trợ giúp gọi là

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
38. Phương pháp này sử dụng hàm
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
39 tích hợp để kiểm tra xem giá trị đầu vào hiện tại có phải là một thể hiện là
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
40,
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
41 hoặc
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
42, là các lớp tích hợp đại diện cho các giá trị số trong Python.

Nếu giá trị đầu vào là một thể hiện của kiểu dữ liệu số, thì hàm trợ giúp của bạn tự trả về chính giá trị. Mặt khác, chức năng tăng ngoại lệ

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
29 với thông báo lỗi thích hợp.

Để sử dụng

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
30, hãy quay lại phiên tương tác của bạn và chạy mã sau:

>>>

>>> from number_list import NumberList

>>> numbers = NumberList([1.1, 2, 3j])
>>> numbers
[1.1, 2, 3j]

>>> numbers.append("4.2")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.append(4.2)
>>> numbers
[1.1, 2, 3j, 4.2]

>>> numbers.insert(0, "0")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.insert(0, 0)
>>> numbers
[0, 1.1, 2, 3j, 4.2]

>>> numbers.extend(["5.3", "6"])
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.extend([5.3, 6])
>>> numbers
[0, 1.1, 2, 3j, 4.2, 5.3, 6]

Trong các ví dụ này, các hoạt động thêm hoặc sửa đổi dữ liệu trong

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
45 tự động xác nhận đầu vào để đảm bảo rằng chỉ có các giá trị số được chấp nhận. Nếu bạn thêm giá trị chuỗi vào
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
45, thì bạn sẽ nhận được
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
29.

Việc triển khai thay thế

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
30 bằng cách sử dụng
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 có thể trông giống như thế này:

# number_list.py

from collections import UserList

class NumberList(UserList):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = self._validate_number(item)

    def insert(self, index, item):
        self.data.insert(index, self._validate_number(item))

    def append(self, item):
        self.data.append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )

Trong triển khai mới này của

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
30, bạn kế thừa từ
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6. Một lần nữa, lớp của bạn sẽ chia sẻ tất cả các chức năng cốt lõi với
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 thông thường.

Trong ví dụ này, thay vì sử dụng

# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
6 tất cả thời gian để truy cập các phương thức và thuộc tính trong lớp cha, bạn sử dụng trực tiếp thuộc tính
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
01. Ở một mức độ nào đó, sử dụng
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
01 có thể đơn giản hóa mã của bạn so với sử dụng
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
6 và các công cụ nâng cao khác như các phương thức đặc biệt.

Lưu ý rằng bạn chỉ sử dụng

# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
6 trong trình khởi tạo lớp,
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
58. Đây là một thực tiễn tốt nhất khi bạn làm việc với kế thừa trong Python. Nó cho phép bạn khởi tạo đúng các thuộc tính trong lớp cha mà không phá vỡ mọi thứ.

Một danh sách có chức năng bổ sung

Bây giờ nói rằng bạn cần một lớp giống như danh sách với tất cả các chức năng tiêu chuẩn của Python

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 thông thường. Lớp học của bạn cũng sẽ cung cấp một số chức năng bổ sung được mượn từ kiểu dữ liệu mảng của JavaScript. Ví dụ: bạn sẽ cần phải có các phương thức như sau:

  • class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    60 kết hợp tất cả các mục trong danh sách trong một chuỗi.
    concatenates all the list’s items in a single string.
  • class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    61 mang lại các mục mới do áp dụng
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    62 có thể gọi được cho mỗi mục trong danh sách cơ bản.
    yields new items that result from applying an
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    62 callable to each item in the underlying list.
  • class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    63 mang lại tất cả các mục trả về
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    64 khi gọi
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    65 trên chúng.
    yields all the items that return
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    64 when calling
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    65 on them.
  • class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    66 gọi
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    67 trên mỗi mục trong danh sách cơ bản để tạo ra một số tác dụng phụ.
    calls
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    67 on every item in the underlying list to generate some side effect.

Ở đây, một lớp thực hiện tất cả các tính năng mới này bằng cách phân lớp

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5:

# custom_list.py

class CustomList(list):
    def join(self, separator=" "):
        return separator.join(str(item) for item in self)

    def map(self, action):
        return type(self)(action(item) for item in self)

    def filter(self, predicate):
        return type(self)(item for item in self if predicate(item))

    def for_each(self, func):
        for item in self:
            func(item)

Phương thức

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
60 trong
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
70 lấy ký tự phân cách làm đối số và sử dụng nó để kết hợp các mục trong đối tượng danh sách hiện tại, được biểu thị bằng
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
71. Để làm điều này, bạn sử dụng
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
72 với biểu thức trình tạo làm đối số. Biểu thức trình tạo này chuyển đổi mọi mục thành một đối tượng chuỗi bằng cách sử dụng
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
73.

Phương thức

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
74 trả về một đối tượng
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
70. Để xây dựng đối tượng này, bạn sử dụng biểu thức trình tạo áp dụng
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
62 cho mọi mục trong đối tượng hiện tại,
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
71. Lưu ý rằng hành động có thể là bất kỳ cuộc gọi nào có thể gọi một mục làm đối số và trả về một mục được chuyển đổi.

Phương thức

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
78 cũng trả về một đối tượng
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
70. Để xây dựng đối tượng này, bạn sử dụng biểu thức máy phát mang lại các mục mà
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
65 trả về
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
64. Trong trường hợp này,
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
65 phải là hàm có giá trị boolean trả về
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
64 hoặc
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
84 tùy thuộc vào các điều kiện nhất định được áp dụng cho mục đầu vào.

Cuối cùng, phương thức

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
85 gọi
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
67 trên mọi mục trong danh sách cơ bản. Cuộc gọi này không trả lời bất cứ điều gì ngoài việc kích hoạt một số tác dụng phụ, như bạn sẽ thấy bên dưới.

Để sử dụng lớp này trong mã của bạn, bạn có thể làm một cái gì đó như sau:

>>>

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
0

Trong các ví dụ này, các hoạt động thêm hoặc sửa đổi dữ liệu trong

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
45 tự động xác nhận đầu vào để đảm bảo rằng chỉ có các giá trị số được chấp nhận. Nếu bạn thêm giá trị chuỗi vào
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
45, thì bạn sẽ nhận được
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
29.

Việc triển khai thay thế

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
30 bằng cách sử dụng
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 có thể trông giống như thế này:

Phương thức

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
78 lấy hàm
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
96 làm đối số. Trong ví dụ, hàm
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
96 này sử dụng
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
98 để chọn những từ bắt đầu bằng tiền tố
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
99. Lưu ý rằng phương pháp này hoạt động tương tự như hàm
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
00 tích hợp, trả về trình lặp thay vì danh sách.

Cuối cùng, cuộc gọi đến

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
85 trên
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
88 in mỗi từ lên màn hình như là một tác dụng phụ của việc gọi
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
03 trên mỗi mục trong danh sách cơ bản. Lưu ý rằng hàm được chuyển đến
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
85 sẽ lấy một mục làm đối số, nhưng nó không nên trả lại bất kỳ giá trị hiệu quả nào.

Bạn cũng có thể thực hiện

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
70 bằng cách kế thừa từ
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 thay vì từ
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5. Trong trường hợp này, bạn không cần phải thay đổi triển khai nội bộ, chỉ là lớp cơ sở:

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
1

Lưu ý rằng trong ví dụ này, bạn chỉ cần thay đổi lớp cha. Không cần phải sử dụng trực tiếp

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
01. Tuy nhiên, bạn có thể sử dụng nó nếu bạn muốn. Ưu điểm là bạn sẽ cung cấp nhiều bối cảnh hơn cho các nhà phát triển khác đọc mã của bạn:

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
2

Trong phiên bản mới này của

# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
09, thay đổi duy nhất là bạn đã thay thế
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
71 bằng
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
11 để làm rõ rằng bạn làm việc với lớp con
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6. Thay đổi này làm cho mã của bạn rõ ràng hơn.

Xem xét hiệu suất: class MyList(list): def __init__(self, *args): list.__init__(self, *args) self.append('FirstMen') self.name = 'Westeros' 5 so với # string_list.py from collections import UserList class StringList(UserList): def __init__(self, iterable): super().__init__(str(item) for item in iterable) def __setitem__(self, index, item): self.data[index] = str(item) def insert(self, index, item): self.data.insert(index, str(item)) def append(self, item): self.data.append(str(item)) def extend(self, other): if isinstance(other, type(self)): self.data.extend(other) else: self.data.extend(str(item) for item in other) 6

Cho đến thời điểm này, bạn đã học được cách tạo các lớp giống như danh sách của riêng mình bằng cách kế thừa từ

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 hoặc
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6. Bạn cũng biết rằng sự khác biệt có thể nhìn thấy duy nhất giữa hai lớp này là
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 phơi bày thuộc tính
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
01, có thể tạo điều kiện thuận lợi cho quá trình mã hóa.

Trong phần này, bạn sẽ xem xét một khía cạnh có thể quan trọng khi quyết định sử dụng

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 hay
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 để tạo các lớp giống như danh sách tùy chỉnh của bạn. Đó là hiệu suất!

Để đánh giá nếu có sự khác biệt về hiệu suất giữa các lớp kế thừa từ

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 so với
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6, bạn sẽ sử dụng lớp
>>> from number_list import NumberList

>>> numbers = NumberList([1.1, 2, 3j])
>>> numbers
[1.1, 2, 3j]

>>> numbers.append("4.2")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.append(4.2)
>>> numbers
[1.1, 2, 3j, 4.2]

>>> numbers.insert(0, "0")
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.insert(0, 0)
>>> numbers
[0, 1.1, 2, 3j, 4.2]

>>> numbers.extend(["5.3", "6"])
Traceback (most recent call last):
    ...
TypeError: numeric value expected, got str

>>> numbers.extend([5.3, 6])
>>> numbers
[0, 1.1, 2, 3j, 4.2, 5.3, 6]
9. Đi trước và tạo một tệp Python mới chứa mã sau:

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
3

Hai lớp này hoạt động giống nhau. Tuy nhiên, họ khác nhau trong nội bộ.

# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
24 kế thừa từ
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 và việc thực hiện nó dựa trên
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
6. Ngược lại,
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
27 kế thừa từ
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 và việc triển khai của nó dựa trên thuộc tính
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
01 nội bộ.

Để so sánh hiệu suất của hai lớp này, bạn nên bắt đầu bằng thời gian các hoạt động danh sách tiêu chuẩn, chẳng hạn như khởi tạo. Tuy nhiên, trong các ví dụ này, cả hai bộ khởi tạo đều tương đương, vì vậy chúng nên thực hiện giống nhau.

Đo thời gian thực hiện của các chức năng mới cũng hữu ích. Ví dụ: bạn có thể kiểm tra thời gian thực hiện của

# number_list.py

from collections import UserList

class NumberList(UserList):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = self._validate_number(item)

    def insert(self, index, item):
        self.data.insert(index, self._validate_number(item))

    def append(self, item):
        self.data.append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )
7. Đi trước và chạy mã sau:

>>>

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
4

Trong thử nghiệm hiệu suất này, bạn sử dụng mô -đun

# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
31 cùng với hàm
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
32 để đo thời gian thực hiện của một đoạn mã. Mã đích bao gồm các cuộc gọi đến
# number_list.py

from collections import UserList

class NumberList(UserList):
    def __init__(self, iterable):
        super().__init__(self._validate_number(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = self._validate_number(item)

    def insert(self, index, item):
        self.data.insert(index, self._validate_number(item))

    def append(self, item):
        self.data.append(self._validate_number(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(self._validate_number(item) for item in other)

    def _validate_number(self, value):
        if isinstance(value, (int, float, complex)):
            return value
        raise TypeError(
            f"numeric value expected, got {type(value).__name__}"
        )
7 trên các trường hợp
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
24 và
# string_list.py

class StringList(list):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        super().__setitem__(index, str(item))

    def insert(self, index, item):
        super().insert(index, str(item))

    def append(self, item):
        super().append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(str(item) for item in other)
27 bằng một số dữ liệu mẫu.

Sự khác biệt về hiệu suất giữa lớp dựa trên

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 và lớp dựa trên
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 chủ yếu không tồn tại trong ví dụ này.

Thông thường, khi bạn tạo một lớp giống như danh sách tùy chỉnh, bạn sẽ mong đợi các lớp con là

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 hoạt động tốt hơn so với các lớp con của
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6. Tại sao? Bởi vì
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 được viết bằng C và được tối ưu hóa cho hiệu suất, trong khi
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 là một lớp trình bao bọc được viết bằng Python Pure Python.

Tuy nhiên, trong ví dụ trên, có vẻ như giả định này không hoàn toàn đúng. Vì lý do này, để quyết định siêu lớp nào là tốt nhất cho trường hợp sử dụng cụ thể của bạn, hãy đảm bảo chạy thử nghiệm hiệu suất.

Hiệu suất sang một bên, kế thừa từ

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 được cho là cách tự nhiên trong Python, chủ yếu là vì
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 có sẵn trực tiếp cho các nhà phát triển Python như một lớp học tích hợp. Ngoài ra, hầu hết các nhà phát triển Python sẽ quen thuộc với các danh sách và các tính năng tiêu chuẩn của họ, điều này sẽ cho phép họ viết các lớp giống như danh sách nhanh hơn.

Ngược lại, lớp

# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 sống trong mô -đun
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
7, có nghĩa là bạn sẽ phải nhập nó nếu bạn muốn sử dụng nó trong mã của mình. Ngoài ra, không phải tất cả các nhà phát triển Python đều biết về sự tồn tại của
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6. Tuy nhiên,
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 vẫn có thể là một công cụ hữu ích vì sự tiện lợi của việc truy cập thuộc tính
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
01, có thể tạo điều kiện cho việc tạo các lớp giống như danh sách tùy chỉnh.

Sự kết luận

Bây giờ bạn đã học được cách tạo các lớp giống như danh sách tùy chỉnh với các hành vi đã sửa đổi và mới. Để làm điều này, bạn đã trực tiếp lớp học được phân lớp

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 tích hợp. Thay vào đó, bạn cũng đã kế thừa từ lớp
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6, có sẵn trong mô -đun
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
7.custom list-like classes with modified and new behaviors. To do this, you’ve subclassed the built-in
class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 class directly. As an alternative, you’ve also inherited from the
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 class, which is available in the
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
7 module.

Kế thừa từ

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
        self.append('FirstMen')
        self.name = 'Westeros'
5 và phân lớp
# string_list.py

from collections import UserList

class StringList(UserList):
    def __init__(self, iterable):
        super().__init__(str(item) for item in iterable)

    def __setitem__(self, index, item):
        self.data[index] = str(item)

    def insert(self, index, item):
        self.data.insert(index, str(item))

    def append(self, item):
        self.data.append(str(item))

    def extend(self, other):
        if isinstance(other, type(self)):
            self.data.extend(other)
        else:
            self.data.extend(str(item) for item in other)
6 đều là những chiến lược phù hợp để tiếp cận vấn đề tạo ra các lớp giống như danh sách của riêng bạn trong Python.

Trong hướng dẫn này, bạn đã học được cách:

  • Tạo các lớp giống như danh sách bằng cách kế thừa từ lớp
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    5 tích hợpbuilt-in
    class MyList(list):
        def __init__(self, *args):
            list.__init__(self, *args)
            self.append('FirstMen')
            self.name = 'Westeros'
    
    5 class
  • Xây dựng các lớp giống như danh sách bằng cách phân lớp
    # string_list.py
    
    from collections import UserList
    
    class StringList(UserList):
        def __init__(self, iterable):
            super().__init__(str(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = str(item)
    
        def insert(self, index, item):
            self.data.insert(index, str(item))
    
        def append(self, item):
            self.data.append(str(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(str(item) for item in other)
    
    6 từ mô-đun
    # string_list.py
    
    from collections import UserList
    
    class StringList(UserList):
        def __init__(self, iterable):
            super().__init__(str(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = str(item)
    
        def insert(self, index, item):
            self.data.insert(index, str(item))
    
        def append(self, item):
            self.data.append(str(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(str(item) for item in other)
    
    7
    # string_list.py
    
    from collections import UserList
    
    class StringList(UserList):
        def __init__(self, iterable):
            super().__init__(str(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = str(item)
    
        def insert(self, index, item):
            self.data.insert(index, str(item))
    
        def append(self, item):
            self.data.append(str(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(str(item) for item in other)
    
    6
    from the
    # string_list.py
    
    from collections import UserList
    
    class StringList(UserList):
        def __init__(self, iterable):
            super().__init__(str(item) for item in iterable)
    
        def __setitem__(self, index, item):
            self.data[index] = str(item)
    
        def insert(self, index, item):
            self.data.insert(index, str(item))
    
        def append(self, item):
            self.data.append(str(item))
    
        def extend(self, other):
            if isinstance(other, type(self)):
                self.data.extend(other)
            else:
                self.data.extend(str(item) for item in other)
    
    7 module

Bây giờ, bạn đã chuẩn bị tốt hơn để tạo danh sách tùy chỉnh của riêng mình, cho phép bạn tận dụng toàn bộ sức mạnh của loại dữ liệu hữu ích và phổ biến này trong Python.