Các chức năng Python có thể bị quá tải không?

Chức năng quá tải trong Python là có thể. Quá tải phương thức trong Python cũng có thể xảy ra. Không trực tiếp, như trong C ++ hoặc Erlang, nhưng nó có thể được thực hiện và nó có thể cứu chúng ta khỏi việc kiểm tra kiểu lớp hoặc kiểu lớp xấu xí để thực thi mã khác phụ thuộc vào kết quả của hàm

>>> vector_slice = vector[2:4]
>>> print(vector_slice, type(vector_slice))
([2, 3], )
7

Hãy xem xét một lớp đơn giản đại diện cho một vectơ có khả năng lấy mục theo chỉ mục (mã Python 3. 10 phù hợp)

class Vector:
def __init__(self, components: list|None = None) -> None:
self._components = components or []
def __getitem__(self, index: int) -> list:
return self._components[index]

Chúng tôi có thể tạo một

>>> vector_slice = vector[2:4]
>>> print(vector_slice, type(vector_slice))
([2, 3], )
8 và chúng tôi có thể lấy một mục theo chỉ mục

>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3

Nhưng những gì về cắt lát?

>>> vector_slice = vector[2:4]
>>> print(vector_slice, type(vector_slice))
([2, 3], )

Hmmm,

>>> vector_slice = vector[2:4]
>>> print(vector_slice, type(vector_slice))
([2, 3], )
8 hỗ trợ cắt lát vì chúng tôi đã triển khai phương pháp
>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3
0, vì vậy python có thể tìm ra những việc cần làm. Tuy nhiên, đây không phải là những gì chúng tôi thực sự muốn.
>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3
0 của chúng tôi là một
>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3
1, nhưng chúng tôi muốn một phần của a
>>> vector_slice = vector[2:4]
>>> print(vector_slice, type(vector_slice))
([2, 3], )
8

Hãy thay đổi phương thức

>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3
0 để nó trả về
>>> vector_slice = vector[2:4]
>>> print(vector_slice, type(vector_slice))
([2, 3], )
8 mới khi cắt

from typing import Unionclass Vector:
def __init__(self, components: list|None = None):
self._components = components
def __getitem__(self, index: Union[int, slice]) -> Union[list, Vector]:
_cls = type(self)
if isinstance(index, slice):
return _cls(components=self._components[index])

elif isinstance(index, int):
return self._components[index]
else:
raise TypeError("list indices must be integers...")

Chúng ta cần kiểm tra xem

>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3
5 là
>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3
6 hay
>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3
7 và nếu đó là
>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3
6 — trả về một đối tượng
>>> vector_slice = vector[2:4]
>>> print(vector_slice, type(vector_slice))
([2, 3], )
8 mới với các thành phần được cắt

Sẽ thật tuyệt nếu loại bỏ các lệnh thực thi

>>> vector_slice = vector[2:4]
>>> print(vector_slice, type(vector_slice))
([2, 3], )
0 và
>>> vector_slice = vector[2:4]
>>> print(vector_slice, type(vector_slice))
([2, 3], )
7 để làm cho mã dễ đọc và sạch hơn. Và loại
>>> vector_slice = vector[2:4]
>>> print(vector_slice, type(vector_slice))
([2, 3], )
2 đó… thật khó hiểu — nếu
>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3
5 là
>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3
7 thì trả về
>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3
1, nhưng nếu là
>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3
6 thì trả lại
>>> vector_slice = vector[2:4]
>>> print(vector_slice, type(vector_slice))
([2, 3], )
8. Trình kiểm tra loại nào có thể xử lý chính xác…?

Có vẻ như đây là một trường hợp sử dụng tốt để sử dụng nạp chồng hàm (hoặc phương thức trong chính trường hợp này), vì vậy chúng ta có thể có một phương thức riêng xử lý các loại tham số

>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3
5 khác nhau. Tái cấu trúc mã để đáp ứng nguyên tắc trách nhiệm duy nhất luôn là một cách để đi

nạp chồng hàm

Hãy để tôi giới thiệu cho bạn một khái niệm gửi đơn

>>> vector = Vector(components=[0,1,2,3,4])
>>> vector[3]
3
7

Chúng tôi có ba lớp đơn giản đại diện cho động vật. Chúng tôi muốn viết một hàm sẽ trả về âm thanh cho một con vật nhất định. Chúng ta có thể làm điều đó bằng cách kiểm tra thể hiện của tham số động vật và trả về chuỗi thích hợp trong một hàm. Nhưng đây là một trường hợp sử dụng tuyệt vời để quá tải hàm

>>> vector_slice = vector[2:4]
>>> print(vector_slice, type(vector_slice))
([2, 3], )
9

Đầu tiên, chúng tôi triển khai một giao diện và trang trí nó bằng một

from typing import Unionclass Vector:
def __init__(self, components: list|None = None):
self._components = components
def __getitem__(self, index: Union[int, slice]) -> Union[list, Vector]:
_cls = type(self)
if isinstance(index, slice):
return _cls(components=self._components[index])

elif isinstance(index, int):
return self._components[index]
else:
raise TypeError("list indices must be integers...")
0 sống trong gói
from typing import Unionclass Vector:
def __init__(self, components: list|None = None):
self._components = components
def __getitem__(self, index: Union[int, slice]) -> Union[list, Vector]:
_cls = type(self)
if isinstance(index, slice):
return _cls(components=self._components[index])

elif isinstance(index, int):
return self._components[index]
else:
raise TypeError("list indices must be integers...")
1. Sau đó, chúng tôi viết càng nhiều hàm
from typing import Unionclass Vector:
def __init__(self, components: list|None = None):
self._components = components
def __getitem__(self, index: Union[int, slice]) -> Union[list, Vector]:
_cls = type(self)
if isinstance(index, slice):
return _cls(components=self._components[index])

elif isinstance(index, int):
return self._components[index]
else:
raise TypeError("list indices must be integers...")
2 càng tốt cho nhiều trường hợp chúng tôi cần xử lý và trang trí mỗi hàm bằng
from typing import Unionclass Vector:
def __init__(self, components: list|None = None):
self._components = components
def __getitem__(self, index: Union[int, slice]) -> Union[list, Vector]:
_cls = type(self)
if isinstance(index, slice):
return _cls(components=self._components[index])

elif isinstance(index, int):
return self._components[index]
else:
raise TypeError("list indices must be integers...")
3. Việc thực hiện các chức năng riêng lẻ có thể thay đổi đáng kể

Để nạp chồng hàm, chúng tôi sử dụng trình trang trí

from typing import Unionclass Vector:
def __init__(self, components: list|None = None):
self._components = components
def __getitem__(self, index: Union[int, slice]) -> Union[list, Vector]:
_cls = type(self)
if isinstance(index, slice):
return _cls(components=self._components[index])

elif isinstance(index, int):
return self._components[index]
else:
raise TypeError("list indices must be integers...")
0, ví dụ: các phương thức có trình trang trí
from typing import Unionclass Vector:
def __init__(self, components: list|None = None):
self._components = components
def __getitem__(self, index: Union[int, slice]) -> Union[list, Vector]:
_cls = type(self)
if isinstance(index, slice):
return _cls(components=self._components[index])

elif isinstance(index, int):
return self._components[index]
else:
raise TypeError("list indices must be integers...")
5. Trong trường hợp ______28, chúng ta có một lớp với phương thức dunder bị quá tải, vì vậy chúng ta sẽ sử dụng cách tiếp cận thứ hai

>>> vector_slice = vector[2:4]
>>> print(vector_slice, type(vector_slice))
([2, 3], )
5

Sạch sẽ hơn nhiều. Tôi nghĩ mã này không cần giải thích…

Có một giải pháp thay thế cho việc gửi một lần. Đó là

from typing import Unionclass Vector:
def __init__(self, components: list|None = None):
self._components = components
def __getitem__(self, index: Union[int, slice]) -> Union[list, Vector]:
_cls = type(self)
if isinstance(index, slice):
return _cls(components=self._components[index])

elif isinstance(index, int):
return self._components[index]
else:
raise TypeError("list indices must be integers...")
7. Bạn có thể kiểm tra xem nó ra ở đây. https. // tài liệu. con trăn. org/3/thư viện/đánh máy. html