Hướng dẫn python custom annotations - chú thích tùy chỉnh python

Tôi đang cố gắng chú thích một biểu đồ xếp chồng lên nhau ở Seaborn với màu sắc cho từng phân đoạn trong biểu đồ vì lý do dễ đọc. Tôi đã đính kèm dữ liệu mẫu bên dưới và những gì tôi hiện đang làm:

Show

Dữ liệu mẫu: https://asyupload.io/as5uxs

Mã hiện tại để tổ chức và hiển thị cốt truyện:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# create the dataframe - from sample data file
data = {'brand': ['Audi', 'Audi', 'Audi', 'Audi', 'Audi', 'Audi', 'Audi', 'Audi', 'Audi', 'BMW', 'BMW', 'BMW', 'BMW', 'BMW', 'GM', 'GM', 'GM', 'GM', 'GM', 'GM', 'Toyota', 'Toyota'],
        'Model': ['A3', 'A3', 'A3', 'A5', 'A5', 'RS5', 'RS5', 'RS5', 'RS5', 'M3', 'M3', 'M3', 'X1', 'X1', 'Chevy', 'Chevy', 'Chevy', 'Chevy', 'Caddy', 'Caddy', 'Camry', 'Corolla']}

data = pd.DataFrame(data)

# make the column categorical, using the order of the 'value_counts'
data['brand'] = pd.Categorical(data['brand'], data['brand'].value_counts(sort=True).index)

# We want to sort the hue value (model) alphabetically
hue_order = data['Model'].unique()
hue_order.sort()

f, ax = plt.subplots(figsize=(10, 6))
sns.histplot(data, x="brand", hue="Model", multiple="stack", edgecolor=".3", linewidth=.5, hue_order=hue_order, ax=ax)

Điều này tạo ra một cốt truyện tốt đẹp với một huyền thoại được đặt hàng và các thanh được đặt hàng. Tuy nhiên, khi tôi thử chú thích bằng một số phương pháp, tôi dường như không thể làm cho nó hoạt động. Những gì tôi theo sau là chú thích có màu sắc, và sau đó là chiều cao của thanh (số lượng xe với nhà sản xuất đó). Vì vậy, ví dụ, đối với thanh đầu tiên, tôi muốn nó hiển thị RS5x 4 trong ô bóng màu xám đầu tiên để trình diễn 4 chiếc xe của mô hình RS5, và cứ thế cho mỗi phân đoạn của biểu đồ xếp chồng lên nhau.

Tôi đã thử rất nhiều phương pháp và đang vật lộn để có được điều này để làm việc. Tôi đã thử sử dụng:

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)

Kết quả hiện tại

Hướng dẫn python custom annotations - chú thích tùy chỉnh python

Nhưng điều này chỉ hiển thị chiều cao của thanh, điều này rất tuyệt, nhưng tôi không chắc làm thế nào để có được văn bản màu sắc chính xác để hiển thị cùng với chiều cao đó.

Bên cạnh tuyên bố

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
7 vừa được giới thiệu, Python sử dụng các câu lệnh điều khiển dòng chảy thông thường được biết đến từ các ngôn ngữ khác, với một số vòng xoắn.

4.1. >>> for i in range(5): ... print(i) ... 0 1 2 3 4 8 Báo cáo Jor>>> for i in range(5): ... print(i) ... 0 1 2 3 4 8 Statements¶

Có lẽ loại tuyên bố nổi tiếng nhất là tuyên bố

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
8. Ví dụ:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More

Có thể không có hoặc nhiều phần

>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
0, và phần
>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
1 là tùy chọn. Từ khóa ‘
>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
0 là viết tắt của‘ nếu không, và rất hữu ích để tránh vết lõm quá mức. Một trình tự
>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
8

Nếu bạn có thể so sánh cùng một giá trị với một số hằng số hoặc kiểm tra các loại hoặc thuộc tính cụ thể, bạn cũng có thể thấy câu lệnh

>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
8 hữu ích. Để biết thêm chi tiết, hãy xem các câu lệnh khớp.match Statements.

4.2. >>> list(range(5, 10)) [5, 6, 7, 8, 9] >>> list(range(0, 10, 3)) [0, 3, 6, 9] >>> list(range(-10, -100, -30)) [-10, -40, -70] 9 Câu lệnh>>> list(range(5, 10)) [5, 6, 7, 8, 9] >>> list(range(0, 10, 3)) [0, 3, 6, 9] >>> list(range(-10, -100, -30)) [-10, -40, -70] 9 Statements¶

Tuyên bố

>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
9 trong Python khác một chút so với những gì bạn có thể quen trong C hoặc Pascal. Thay vì luôn lặp đi lặp lại về sự tiến triển số học của các số (như trong pascal) hoặc cho người dùng khả năng xác định cả bước lặp và điều kiện tạm dừng (như C), câu lệnh
>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
9 của Python lặp lại các mục của bất kỳ chuỗi nào (danh sách hoặc một chuỗi), theo thứ tự chúng xuất hiện trong chuỗi. Ví dụ (không có ý định chơi chữ):

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12

Mã sửa đổi một bộ sưu tập trong khi lặp lại trên cùng một bộ sưu tập có thể là khó khăn để có được đúng. Thay vào đó, thường là lặp đi về phía trước để lặp qua một bản sao của bộ sưu tập hoặc để tạo một bộ sưu tập mới:

# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status

4.3. Hàm >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print(i, a[i]) ... 0 Mary 1 had 2 a 3 little 4 lamb 2The >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print(i, a[i]) ... 0 Mary 1 had 2 a 3 little 4 lamb 2 Function¶

Nếu bạn cần lặp lại một chuỗi các số, hàm tích hợp

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
2 có ích. Nó tạo ra các tiến trình số học:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

Điểm cuối đã cho không bao giờ là một phần của chuỗi được tạo ra;

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
4 tạo ra 10 giá trị, các chỉ số pháp lý cho các mục có chuỗi độ dài 10. Có thể để phạm vi bắt đầu ở một số khác hoặc để chỉ định một mức tăng khác (thậm chí âm; đôi khi điều này được gọi là ‘bước,):

>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]

Để lặp lại các chỉ số của một chuỗi, bạn có thể kết hợp

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
2 và
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
6 như sau:

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

Tuy nhiên, trong hầu hết các trường hợp như vậy, việc sử dụng hàm

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
7 là thuận tiện, xem các kỹ thuật lặp.Looping Techniques.

Một điều kỳ lạ xảy ra nếu bạn chỉ in một phạm vi:

>>> range(10)
range(0, 10)

Theo nhiều cách, đối tượng được trả về bởi

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
2 hành xử như thể đó là một danh sách, nhưng thực tế nó không phải là. Đó là một đối tượng trả về các mục liên tiếp của chuỗi mong muốn khi bạn lặp lại nó, nhưng nó không thực sự tạo ra danh sách, do đó tiết kiệm không gian.

Chúng tôi nói một đối tượng như vậy là có thể sử dụng được, nghĩa là phù hợp như một mục tiêu cho các chức năng và cấu trúc mong đợi một cái gì đó mà chúng có thể có được các mặt hàng liên tiếp cho đến khi nguồn cung bị cạn kiệt. Chúng tôi đã thấy rằng câu lệnh

>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
9 là một cấu trúc như vậy, trong khi một ví dụ về một hàm có thể điều chỉnh được là
>>> range(10)
range(0, 10)
0:iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the
>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
9 statement is such a construct, while an example of a function that takes an iterable is
>>> range(10)
range(0, 10)
0:

>>> sum(range(4))  # 0 + 1 + 2 + 3
6

Sau đó, chúng ta sẽ thấy nhiều chức năng trả về Iterables và lấy Iterables làm đối số. Trong các cấu trúc dữ liệu chương, chúng tôi sẽ thảo luận chi tiết hơn về

>>> range(10)
range(0, 10)
1.Data Structures, we will discuss in more detail about
>>> range(10)
range(0, 10)
1.

4.4. Các câu lệnh >>> range(10) range(0, 10) 2 và >>> range(10) range(0, 10) 3 và các điều khoản >>> list(range(5, 10)) [5, 6, 7, 8, 9] >>> list(range(0, 10, 3)) [0, 3, 6, 9] >>> list(range(-10, -100, -30)) [-10, -40, -70] 1 trên Loops¶>>> range(10) range(0, 10) 2 and >>> range(10) range(0, 10) 3 Statements, and >>> list(range(5, 10)) [5, 6, 7, 8, 9] >>> list(range(0, 10, 3)) [0, 3, 6, 9] >>> list(range(-10, -100, -30)) [-10, -40, -70] 1 Clauses on Loops¶

Tuyên bố

>>> range(10)
range(0, 10)
2, như trong C, thoát ra khỏi vòng lặp
>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
9 hoặc
>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
7.

Các câu lệnh Loop có thể có mệnh đề

>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
1; Nó được thực hiện khi vòng lặp chấm dứt thông qua sự kiệt sức của điều đáng tin (với
>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
9) hoặc khi điều kiện trở thành sai (với
>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
7), nhưng không phải khi vòng lặp bị chấm dứt bởi câu lệnh
>>> range(10)
range(0, 10)
2. Điều này được minh họa bằng vòng lặp sau, tìm kiếm số nguyên tố:

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
0

.not the

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
8 statement.)

Khi được sử dụng với một vòng lặp, mệnh đề

>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
1 có nhiều điểm chung với mệnh đề
>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
1 của câu lệnh
>>> sum(range(4))  # 0 + 1 + 2 + 3
6
7 so với các câu lệnh
>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
8 xảy ra. Để biết thêm về tuyên bố và ngoại lệ
>>> sum(range(4))  # 0 + 1 + 2 + 3
6
7, hãy xem các ngoại lệ xử lý.Handling Exceptions.

Tuyên bố

>>> range(10)
range(0, 10)
3, cũng mượn từ C, tiếp tục với lần lặp tiếp theo của vòng lặp:

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
1

4.5. for i, rect in enumerate(ax.patches): # Find where everything is located height = rect.get_height() width = rect.get_width() x = rect.get_x() y = rect.get_y() # The height of the bar is the count value and can used as the label label_text = f'{height:.0f}' label_x = x + width / 2 label_y = y + height / 2 # don't include label if it's equivalently 0 if height > 0.001: ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8) 05 Báo cáo Jorfor i, rect in enumerate(ax.patches): # Find where everything is located height = rect.get_height() width = rect.get_width() x = rect.get_x() y = rect.get_y() # The height of the bar is the count value and can used as the label label_text = f'{height:.0f}' label_x = x + width / 2 label_y = y + height / 2 # don't include label if it's equivalently 0 if height > 0.001: ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8) 05 Statements¶

Tuyên bố

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
05 không làm gì cả. Nó có thể được sử dụng khi một câu lệnh được yêu cầu về mặt cú pháp nhưng chương trình không yêu cầu hành động. Ví dụ:

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
2

Điều này thường được sử dụng để tạo các lớp tối thiểu:

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
3

Một nơi khác

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
05 có thể được sử dụng là một người giữ chỗ cho một chức năng hoặc cơ thể có điều kiện khi bạn đang làm việc trên mã mới, cho phép bạn tiếp tục suy nghĩ ở cấp độ trừu tượng hơn.
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
05 âm thầm bị bỏ qua:

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
4

4.6. >>> list(range(5, 10)) [5, 6, 7, 8, 9] >>> list(range(0, 10, 3)) [0, 3, 6, 9] >>> list(range(-10, -100, -30)) [-10, -40, -70] 8 Báo cáo Jor>>> list(range(5, 10)) [5, 6, 7, 8, 9] >>> list(range(0, 10, 3)) [0, 3, 6, 9] >>> list(range(-10, -100, -30)) [-10, -40, -70] 8 Statements¶

Một câu lệnh

>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
8 lấy một biểu thức và so sánh giá trị của nó với các mẫu liên tiếp được đưa ra dưới dạng một hoặc nhiều khối trường hợp. Điều này tương tự hời hợt với câu lệnh Switch trong C, Java hoặc JavaScript (và nhiều ngôn ngữ khác), nhưng nó giống với khớp mẫu phù hợp bằng các ngôn ngữ như Rust hoặc Haskell. Chỉ mẫu đầu tiên phù hợp được thực thi và nó cũng có thể trích xuất các thành phần (phần tử trình tự hoặc thuộc tính đối tượng) từ giá trị thành các biến.

Hình thức đơn giản nhất so sánh giá trị chủ đề với một hoặc nhiều chữ:

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
5

Lưu ý Khối cuối cùng: Tên biến có thể thay đổi

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
11 hoạt động như một ký tự đại diện và không bao giờ thất bại để phù hợp. Nếu không có trường hợp nào phù hợp, không có chi nhánh nào được thực hiện.

Bạn có thể kết hợp một số chữ theo một mẫu bằng cách sử dụng

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
12 (về hoặc hoặc):

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
6

Các mẫu có thể trông giống như các bài tập giải nén và có thể được sử dụng để liên kết các biến:

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
7

Nghiên cứu một cách cẩn thận! Mẫu đầu tiên có hai chữ, và có thể được coi là một phần mở rộng của mẫu theo nghĩa đen được hiển thị ở trên. Nhưng hai mẫu tiếp theo kết hợp một nghĩa đen và một biến, và biến liên kết một giá trị từ đối tượng (

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
13). Mẫu thứ tư nắm bắt hai giá trị, làm cho nó tương tự về mặt khái niệm với gán giải nén
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
14.

Nếu bạn đang sử dụng các lớp để cấu trúc dữ liệu của mình, bạn có thể sử dụng tên lớp theo sau là danh sách đối số giống như một hàm tạo, nhưng với khả năng nắm bắt các thuộc tính thành các biến:

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
8

Bạn có thể sử dụng các tham số vị trí với một số lớp tích hợp cung cấp đặt hàng cho các thuộc tính của chúng (ví dụ: DataClasses). Bạn cũng có thể xác định một vị trí cụ thể cho các thuộc tính trong các mẫu bằng cách đặt thuộc tính đặc biệt

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
15 trong các lớp của bạn. Nếu nó được đặt thành ((X X,

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
9

Một cách được đề xuất để đọc các mẫu là xem chúng như một hình thức mở rộng của những gì bạn sẽ đặt ở bên trái của một bài tập, để hiểu các biến nào sẽ được đặt thành những gì. Chỉ các tên độc lập (như

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
17 ở trên) được gán cho một câu lệnh khớp. Các tên chấm chấm (như
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
19), tên thuộc tính (
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
20 và
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
21 ở trên) hoặc tên lớp (được công nhận bởi ((một)) bên cạnh chúng như
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
22 ở trên) không bao giờ được gán.

Các mẫu có thể được lồng tùy ý. Ví dụ: nếu chúng ta có một danh sách ngắn các điểm, chúng ta có thể khớp nó như thế này:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
0

Chúng ta có thể thêm một điều khoản

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
8 vào một mẫu, được gọi là một người bảo vệ. Nếu người bảo vệ sai,
>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
8 tiếp tục thử khối trường hợp tiếp theo. Lưu ý rằng việc bắt giá trị xảy ra trước khi người bảo vệ được đánh giá:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
1

Một số tính năng chính khác của câu lệnh này:

  • Giống như giải nén các bài tập, các mẫu Tuple và List có cùng một ý nghĩa và thực sự phù hợp với các chuỗi tùy ý. Một ngoại lệ quan trọng là họ không phù hợp với trình lặp hoặc dây.

  • Các mẫu chuỗi hỗ trợ mở rộng Giải nén:

    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    25 và
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    26 hoạt động tương tự như các bài tập giải nén. Tên sau
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    27 cũng có thể là
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    11, do đó
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    29 khớp với một chuỗi ít nhất hai mục mà không ràng buộc các mục còn lại.

  • Các mẫu ánh xạ:

    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    30 nắm bắt các giá trị
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    31 và
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    32 từ một từ điển. Không giống như các mẫu trình tự, các khóa phụ bị bỏ qua. Một việc giải nén như
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    33 cũng được hỗ trợ. (Nhưng
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    34 sẽ dư thừa, vì vậy nó không được phép.)

  • Tiểu nhà có thể được ghi lại bằng từ khóa

    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    35:

    >>> x = int(input("Please enter an integer: "))
    Please enter an integer: 42
    >>> if x < 0:
    ...     x = 0
    ...     print('Negative changed to zero')
    ... elif x == 0:
    ...     print('Zero')
    ... elif x == 1:
    ...     print('Single')
    ... else:
    ...     print('More')
    ...
    More
    
    2

    sẽ nắm bắt phần tử thứ hai của đầu vào là

    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    36 (miễn là đầu vào là một chuỗi hai điểm)

  • Hầu hết các chữ được so sánh bằng sự bình đẳng, tuy nhiên các singletons

    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    37,
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    38 và
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    39 được so sánh bằng danh tính.

  • Các mẫu có thể sử dụng hằng số được đặt tên. Đây phải là những cái tên chấm để ngăn chúng được hiểu là biến bắt giữ:

    >>> x = int(input("Please enter an integer: "))
    Please enter an integer: 42
    >>> if x < 0:
    ...     x = 0
    ...     print('Negative changed to zero')
    ... elif x == 0:
    ...     print('Zero')
    ... elif x == 1:
    ...     print('Single')
    ... else:
    ...     print('More')
    ...
    More
    
    3

Để giải thích chi tiết hơn và các ví dụ bổ sung, bạn có thể xem xét PEP 636 được viết theo định dạng hướng dẫn.PEP 636 which is written in a tutorial format.

4.7. Xác định chức năng JoDefining Functions¶

Chúng ta có thể tạo một chức năng viết chuỗi Fibonacci vào một ranh giới tùy ý:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
4

Từ khóa

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
40 giới thiệu một định nghĩa chức năng. Nó phải được theo sau bởi tên hàm và danh sách dấu ngoặc đơn của các tham số chính thức. Các câu lệnh tạo thành phần thân của hàm bắt đầu ở dòng tiếp theo và phải được thụt vào.

Câu lệnh đầu tiên của cơ thể chức năng có thể tùy ý là một chuỗi theo nghĩa đen; Chuỗi này theo nghĩa đen là chuỗi tài liệu của chức năng, hoặc DocString. . Nó thực hành tốt để bao gồm các tài liệu trong mã mà bạn viết, vì vậy hãy tạo thói quen cho nó.Documentation Strings.) There are tools which use docstrings to automatically produce online or printed documentation, or to let the user interactively browse through code; it’s good practice to include docstrings in code that you write, so make a habit of it.

Việc thực hiện một hàm giới thiệu một bảng biểu tượng mới được sử dụng cho các biến cục bộ của hàm. Chính xác hơn, tất cả các bài tập biến trong một hàm lưu trữ giá trị trong bảng ký hiệu cục bộ; Trong khi các tham chiếu biến đổi đầu tiên trong bảng biểu tượng cục bộ, thì trong các bảng ký hiệu cục bộ của các hàm bao quanh, sau đó trong bảng biểu tượng toàn cầu và cuối cùng trong bảng các tên tích hợp. Do đó, các biến và biến toàn cầu của các hàm bao quanh không thể được gán trực tiếp một giá trị trong một hàm (trừ khi, đối với các biến toàn cầu, được đặt tên trong câu lệnh

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
41, hoặc, đối với các biến số của các hàm, được đặt tên trong câu lệnh
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
42), mặc dù chúng có thể là tham chiếu.

Các tham số thực tế (đối số) cho một cuộc gọi hàm được giới thiệu trong bảng ký hiệu cục bộ của hàm được gọi là khi nó được gọi; Do đó, các đối số được truyền bằng cách sử dụng cuộc gọi theo giá trị (trong đó giá trị luôn là tham chiếu đối tượng, không phải là giá trị của đối tượng). 1 Khi một hàm gọi hàm khác hoặc tự gọi theo cách đệ quy, một bảng ký hiệu cục bộ mới được tạo cho cuộc gọi đó.

Một định nghĩa chức năng liên kết tên hàm với đối tượng hàm trong bảng ký hiệu hiện tại. Trình thông dịch nhận ra đối tượng được chỉ ra bởi tên đó là hàm do người dùng xác định. Các tên khác cũng có thể trỏ đến cùng đối tượng chức năng đó và cũng có thể được sử dụng để truy cập chức năng:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
5

Đến từ các ngôn ngữ khác, bạn có thể phản đối rằng

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
43 không phải là một hàm mà là một thủ tục vì nó không trả về một giá trị. Trên thực tế, ngay cả các chức năng mà không có câu lệnh
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
44 trả về một giá trị, mặc dù là một câu nói khá nhàm chán. Giá trị này được gọi là
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
39 (nó là một tên tích hợp). Viết giá trị
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
39 thường bị người phiên dịch triệt tiêu nếu đó là giá trị duy nhất được viết. Bạn có thể thấy nó nếu bạn thực sự muốn sử dụng
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
47:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
6

Thật đơn giản để viết một hàm trả về danh sách các số của loạt Fibonacci, thay vì in nó:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
7

Ví dụ này, như thường lệ, chứng minh một số tính năng Python mới:

  • Câu lệnh

    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    44 trả về với giá trị từ một hàm.
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    44 mà không có đối số biểu thức trả về
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    39. Rơi ra khỏi cuối một hàm cũng trả về
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    39.

  • Câu lệnh

    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    52 gọi một phương thức của đối tượng danh sách
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    53. Một phương pháp là một hàm ‘thuộc về một đối tượng và được đặt tên là
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    54, trong đó
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    55 là một số đối tượng (đây có thể là một biểu thức) và
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    56 là tên của một phương thức được xác định bởi loại đối tượng. Các loại khác nhau xác định các phương pháp khác nhau. Các phương pháp của các loại khác nhau có thể có cùng tên mà không gây ra sự mơ hồ. . Nó thêm một yếu tố mới ở cuối danh sách. Trong ví dụ này, nó tương đương với
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    58, nhưng hiệu quả hơn.Classes) The method
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    57 shown in the example is defined for list objects; it adds a new element at the end of the list. In this example it is equivalent to
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    58, but more efficient.

4.8. Thêm về việc xác định chức năng JoMore on Defining Functions¶

Cũng có thể xác định các chức năng với số lượng đối số thay đổi. Có ba hình thức, có thể được kết hợp.

4.8.1. Giá trị đối số mặc định JoDefault Argument Values¶

Biểu mẫu hữu ích nhất là chỉ định giá trị mặc định cho một hoặc nhiều đối số. Điều này tạo ra một hàm có thể được gọi với ít đối số hơn nó được xác định để cho phép. Ví dụ:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
8

Chức năng này có thể được gọi theo nhiều cách:

  • Chỉ đưa ra lập luận bắt buộc:

    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    59

  • Đưa ra một trong những đối số tùy chọn:

    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    60

  • hoặc thậm chí đưa ra tất cả các lập luận:

    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    
    61

Ví dụ này cũng giới thiệu từ khóa

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
62. Điều này kiểm tra xem một chuỗi có chứa một giá trị nhất định hay không.

Các giá trị mặc định được đánh giá tại điểm định nghĩa hàm trong phạm vi xác định, do đó

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
9

Sẽ in

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
63.

Cảnh báo quan trọng: Giá trị mặc định chỉ được đánh giá một lần. Điều này tạo ra sự khác biệt khi mặc định là một đối tượng có thể thay đổi như danh sách, từ điển hoặc phiên bản của hầu hết các lớp. Ví dụ: hàm sau tích lũy các đối số được truyền cho nó trong các cuộc gọi tiếp theo: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12
0

Điều này sẽ in

Nếu bạn không muốn mặc định được chia sẻ giữa các cuộc gọi tiếp theo, bạn có thể viết chức năng như thế này: thay vào đó:

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12
1

4.8.2. Từ khóa đối sốKeyword Arguments¶

Các chức năng cũng có thể được gọi là bằng cách sử dụng các đối số từ khóa của mẫu

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
64. Chẳng hạn, chức năng sau:keyword arguments of the form
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
64. For instance, the following function:

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12
2

Chấp nhận một đối số bắt buộc (

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
65) và ba đối số tùy chọn (
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
66,
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
67 và
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
68). Hàm này có thể được gọi theo bất kỳ cách nào sau đây:

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12
3

Nhưng tất cả các cuộc gọi sau đây sẽ không hợp lệ:

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12
4

Trong một cuộc gọi chức năng, các đối số từ khóa phải tuân theo các đối số vị trí. Tất cả các đối số từ khóa được truyền phải khớp với một trong các đối số được chấp nhận bởi hàm (ví dụ:

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
69 không phải là một đối số hợp lệ cho hàm
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
70) và thứ tự của chúng không quan trọng. Điều này cũng bao gồm các đối số không tùy chọn (ví dụ:
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
71 cũng hợp lệ). Không có đối số có thể nhận được một giá trị nhiều hơn một lần. Ở đây, một ví dụ thất bại do hạn chế này:

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12
5

Khi có tham số chính thức cuối cùng của Mẫu

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
72, nó sẽ nhận được một từ điển (xem các loại ánh xạ - Dict) chứa tất cả các đối số từ khóa ngoại trừ các đối số tương ứng với một tham số chính thức. Điều này có thể được kết hợp với một tham số chính thức của mẫu
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
73 (được mô tả trong tiểu mục tiếp theo) nhận được một bộ chứa các đối số vị trí ngoài danh sách tham số chính thức. (
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
73 phải xảy ra trước
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
72.) Ví dụ, nếu chúng ta xác định một hàm như thế này:Mapping Types — dict) containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
73 (described in the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list. (
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
73 must occur before
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
72.) For example, if we define a function like this:

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12
6

Nó có thể được gọi như thế này:

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12
7

Và tất nhiên nó sẽ in:

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12
8

Lưu ý rằng thứ tự trong đó các đối số từ khóa được in được đảm bảo để phù hợp với thứ tự mà chúng được cung cấp trong cuộc gọi chức năng.

4.8.3. Thông số đặc biệtSpecial parameters¶

Theo mặc định, các đối số có thể được chuyển đến hàm Python theo vị trí hoặc rõ ràng bằng từ khóa. Đối với khả năng đọc và hiệu suất, có ý nghĩa khi hạn chế cách các đối số có thể được thông qua để nhà phát triển chỉ cần nhìn vào định nghĩa chức năng để xác định xem các mục được truyền theo vị trí, theo vị trí hoặc từ khóa hoặc từ khóa.

Một định nghĩa chức năng có thể trông giống như:

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12
9

trong đó

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
76 và
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
27 là tùy chọn. Nếu được sử dụng, các ký hiệu này chỉ ra loại tham số bằng cách các đối số có thể được truyền đến hàm: chỉ có vị trí, vị trí hoặc từ khóa và chỉ từ khóa. Các tham số từ khóa cũng được gọi là tham số được đặt tên.

4.8.3.1. Đối số về vị trí hoặc thông sốPositional-or-Keyword Arguments¶

Nếu

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
76 và
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
27 không có trong định nghĩa hàm, các đối số có thể được truyền đến một hàm theo vị trí hoặc từ khóa.

4.8.3.2. Tham số chỉ có vị tríPositional-Only Parameters¶

Nhìn vào điều này chi tiết hơn một chút, có thể đánh dấu các tham số nhất định là chỉ có vị trí. Nếu chỉ có vị trí, các tham số có vấn đề về thứ tự và các tham số không thể được truyền bằng từ khóa. Các tham số chỉ có vị trí được đặt trước một

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
76 (slash phía trước).
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
76 được sử dụng để phân tách hợp lý các tham số chỉ có vị trí với phần còn lại của các tham số. Nếu không có
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
76 trong định nghĩa hàm, không có tham số chỉ có vị trí.

Các tham số sau

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
76 có thể là từ vị trí hoặc từ khóa chỉ.

4.8.3.3. Đối số chỉ dành cho từ khóaKeyword-Only Arguments¶

Để đánh dấu các tham số là chỉ từ khóa, chỉ ra các tham số phải được truyền bằng đối số từ khóa, hãy đặt một

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
27 trong danh sách đối số ngay trước tham số chỉ từ khóa đầu tiên.

4.8.3.4. Ví dụ chức năng JoFunction Examples¶

Hãy xem xét các định nghĩa chức năng ví dụ sau đây chú ý đến các điểm đánh dấu

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
76 và
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
27:

# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status
0

Định nghĩa chức năng đầu tiên,

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
87, hình thức quen thuộc nhất, không có hạn chế nào đối với quy ước gọi và đối số có thể được truyền qua vị trí hoặc từ khóa:

# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status
1

Hàm thứ hai

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
88 bị hạn chế chỉ sử dụng các tham số vị trí vì có
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
76 trong định nghĩa chức năng:

# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status
2

Hàm thứ ba

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
90 chỉ cho phép các đối số từ khóa được biểu thị bằng
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
27 trong định nghĩa hàm:

# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status
3

Và lần cuối cùng sử dụng cả ba quy ước gọi trong cùng một định nghĩa chức năng:

# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status
4

Cuối cùng, hãy xem xét định nghĩa chức năng này có sự va chạm tiềm năng giữa đối số vị trí

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
92 và
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
93 có
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
92 làm chìa khóa:

# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status
5

Không có cuộc gọi nào có thể làm cho nó trả về

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
37 vì từ khóa
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
96 sẽ luôn liên kết với tham số đầu tiên. Ví dụ:

# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status
6

Nhưng sử dụng

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
76 (đối số chỉ có vị trí), có thể vì nó cho phép
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
92 làm đối số vị trí và
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
96 làm khóa trong các đối số từ khóa:

# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status
7

Nói cách khác, tên của các tham số chỉ có vị trí có thể được sử dụng trong

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
93 mà không có sự mơ hồ.

4.8.3.5. Tóm tắt lại¶Recap¶

Trường hợp sử dụng sẽ xác định sử dụng tham số nào trong định nghĩa hàm:

# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status
8

Theo hướng dẫn:

  • Sử dụng chỉ vị trí nếu bạn muốn tên của các tham số không có sẵn cho người dùng. Điều này rất hữu ích khi tên tham số không có ý nghĩa thực sự, nếu bạn muốn thực thi thứ tự của các đối số khi hàm được gọi hoặc nếu bạn cần lấy một số tham số vị trí và từ khóa tùy ý.

  • Sử dụng từ khóa chỉ khi tên có ý nghĩa và định nghĩa hàm dễ hiểu hơn bằng cách rõ ràng với tên hoặc bạn muốn ngăn người dùng dựa vào vị trí của đối số được truyền.

  • Đối với API, hãy sử dụng chỉ có vị trí để ngăn chặn các thay đổi API nếu tên tham số được sửa đổi trong tương lai.

4.8.4. Danh sách lập luận tùy ýArbitrary Argument Lists¶

Cuối cùng, tùy chọn ít được sử dụng nhất là chỉ định rằng một hàm có thể được gọi với số lượng đối số tùy ý. Những đối số này sẽ được kết thúc thành một tuple (xem các bộ dữ liệu và trình tự). Trước khi có số lượng đối số, không có hoặc nhiều đối số bình thường hơn có thể xảy ra.Tuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur.

# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status
9

Thông thường, các đối số variadic này sẽ là lần cuối cùng trong danh sách các tham số chính thức, bởi vì chúng tìm ra tất cả các đối số đầu vào còn lại được truyền cho hàm. Bất kỳ tham số chính thức nào xảy ra sau tham số

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
01 là các đối số chỉ từ khóa, có nghĩa là chúng chỉ có thể được sử dụng làm từ khóa thay vì đối số vị trí.

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
0

4.8.5. Giải nén Danh sách đối sốUnpacking Argument Lists¶

Tình huống ngược lại xảy ra khi các đối số đã nằm trong danh sách hoặc tuple nhưng cần phải được giải nén cho một cuộc gọi chức năng yêu cầu các đối số vị trí riêng biệt. Chẳng hạn, hàm

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
2 tích hợp mong đợi các đối số bắt đầu và dừng riêng biệt. Nếu chúng không có sẵn một cách riêng biệt, hãy viết cuộc gọi chức năng với ____ 127 người vận hành để giải nén các đối số ra khỏi danh sách hoặc tuple:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
1

Trong cùng một thời trang, từ điển có thể cung cấp các đối số từ khóa với ____ 204-coperator:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
2

4.8.6. Biểu thức Lambda¶Lambda Expressions¶

Các hàm ẩn danh nhỏ có thể được tạo với từ khóa

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
05. Hàm này trả về tổng của hai đối số của nó:
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
06. Các hàm Lambda có thể được sử dụng bất cứ nơi nào các đối tượng chức năng được yêu cầu. Chúng bị giới hạn về mặt cú pháp trong một biểu thức duy nhất. Về mặt ngữ nghĩa, chúng chỉ là đường cú pháp cho một định nghĩa chức năng bình thường. Giống như các định nghĩa chức năng lồng nhau, các hàm Lambda có thể tham chiếu các biến từ phạm vi chứa:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
3

Ví dụ trên sử dụng biểu thức lambda để trả về một hàm. Một cách sử dụng khác là chuyển một chức năng nhỏ như một đối số:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
4

4.8.7. Chuỗi tài liệuDocumentation Strings¶

Dưới đây là một số quy ước về nội dung và định dạng của chuỗi tài liệu.

Dòng đầu tiên phải luôn luôn là một bản tóm tắt ngắn gọn, ngắn gọn về mục đích của đối tượng. Đối với sự ngắn gọn, nó không nên nêu rõ ràng tên hoặc loại đối tượng, vì chúng có sẵn bằng các phương tiện khác (trừ khi tên xảy ra là một động từ mô tả hoạt động của chức năng). Dòng này nên bắt đầu bằng một chữ cái viết hoa và kết thúc bằng một khoảng thời gian.

Nếu có nhiều dòng hơn trong chuỗi tài liệu, dòng thứ hai phải trống, phân tách trực quan bản tóm tắt với phần còn lại của mô tả. Các dòng sau đây phải là một hoặc nhiều đoạn mô tả các quy ước gọi đối tượng, các tác dụng phụ của nó, v.v.

Trình phân tích cú pháp Python không thoát khỏi thụt lề từ các chuỗi chuỗi đa dòng trong Python, do đó, các công cụ mà tài liệu xử lý phải dải thụt vào nếu muốn. Điều này được thực hiện bằng cách sử dụng quy ước sau. Dòng không trống đầu tiên sau dòng đầu tiên của chuỗi xác định lượng thụt vào toàn bộ chuỗi tài liệu. . . Các dòng được thụt vào ít hơn không nên xảy ra, nhưng nếu chúng xảy ra tất cả khoảng trắng hàng đầu của chúng nên bị tước. Tương đương của khoảng trắng phải được kiểm tra sau khi mở rộng các tab (đến 8 khoảng trống, thông thường).

Dưới đây là một ví dụ về tài liệu đa dòng:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
5

4.8.8. Chú thích chức năngFunction Annotations¶

Chú thích chức năng là thông tin siêu dữ liệu hoàn toàn tùy chọn về các loại được sử dụng bởi các chức năng do người dùng xác định (xem PEP 3107 và PEP 484 để biết thêm thông tin). are completely optional metadata information about the types used by user-defined functions (see PEP 3107 and PEP 484 for more information).

Các chú thích được lưu trữ trong thuộc tính

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
07 của hàm dưới dạng từ điển và không có tác dụng đối với bất kỳ phần nào khác của hàm. Các chú thích tham số được xác định bởi một dấu hai chấm sau tên tham số, theo sau là một biểu thức đánh giá theo giá trị của chú thích. Các chú thích trả lại được xác định bởi một
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
08 theo nghĩa đen, theo sau là một biểu thức, giữa danh sách tham số và đại tràng biểu thị kết thúc của câu lệnh
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
40. Ví dụ sau có một đối số bắt buộc, đối số tùy chọn và giá trị trả về được chú thích: are stored in the
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
07 attribute of the function as a dictionary and have no effect on any other part of the function. Parameter annotations are defined by a colon after the parameter name, followed by an expression evaluating to the value of the annotation. Return annotations are defined by a literal
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
08, followed by an expression, between the parameter list and the colon denoting the end of the
for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()

    # The height of the bar is the count value and can used as the label
    label_text = f'{height:.0f}'

    label_x = x + width / 2
    label_y = y + height / 2

    # don't include label if it's equivalently 0
    if height > 0.001:
        ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
40 statement. The following example has a required argument, an optional argument, and the return value annotated:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
6

4.9. Intermezzo: Kiểu mãIntermezzo: Coding Style¶

Bây giờ bạn sắp viết những mảnh python dài hơn, phức tạp hơn, đây là thời điểm tốt để nói về phong cách mã hóa. Hầu hết các ngôn ngữ có thể được viết (hoặc súc tích hơn, được định dạng) theo các phong cách khác nhau; Một số dễ đọc hơn những người khác. Làm cho người khác dễ dàng đọc mã của bạn luôn là một ý tưởng tốt, và việc áp dụng một phong cách mã hóa đẹp giúp rất nhiều cho điều đó.

Đối với Python, Pep 8 đã nổi lên như một hướng dẫn phong cách mà hầu hết các dự án tuân thủ; Nó thúc đẩy một phong cách mã hóa rất dễ đọc và làm hài lòng. Mỗi nhà phát triển Python nên đọc nó tại một số điểm; Dưới đây là những điểm quan trọng nhất được trích xuất cho bạn:PEP 8 has emerged as the style guide that most projects adhere to; it promotes a very readable and eye-pleasing coding style. Every Python developer should read it at some point; here are the most important points extracted for you:

  • Sử dụng thụt 4 không gian, và không có tab.

    4 không gian là một sự thỏa hiệp tốt giữa vết lõm nhỏ (cho phép độ sâu làm tổ lớn hơn) và thụt lớn (dễ đọc hơn). Các tab giới thiệu nhầm lẫn, và tốt nhất là bị bỏ rơi.

  • Bao bọc các dòng để chúng không vượt quá 79 ký tự.

    Điều này giúp người dùng có màn hình nhỏ và có thể có một số tệp mã bên cạnh các màn hình lớn hơn.

  • Sử dụng các dòng trống để phân tách các chức năng và các lớp và các khối mã bên trong các chức năng lớn hơn.

  • Khi có thể, hãy đặt ý kiến ​​trên một dòng của riêng họ.

  • Sử dụng tài liệu.

  • Sử dụng không gian xung quanh các toán tử và sau dấu phẩy, nhưng không trực tiếp bên trong các cấu trúc khung:

    >>> x = int(input("Please enter an integer: "))
    Please enter an integer: 42
    >>> if x < 0:
    ...     x = 0
    ...     print('Negative changed to zero')
    ... elif x == 0:
    ...     print('Zero')
    ... elif x == 1:
    ...     print('Single')
    ... else:
    ...     print('More')
    ...
    More
    
    10.

  • Đặt tên cho các lớp học và chức năng của bạn một cách nhất quán; Công ước là sử dụng

    >>> x = int(input("Please enter an integer: "))
    Please enter an integer: 42
    >>> if x < 0:
    ...     x = 0
    ...     print('Negative changed to zero')
    ... elif x == 0:
    ...     print('Zero')
    ... elif x == 1:
    ...     print('Single')
    ... else:
    ...     print('More')
    ...
    More
    
    11 cho các lớp và
    >>> x = int(input("Please enter an integer: "))
    Please enter an integer: 42
    >>> if x < 0:
    ...     x = 0
    ...     print('Negative changed to zero')
    ... elif x == 0:
    ...     print('Zero')
    ... elif x == 1:
    ...     print('Single')
    ... else:
    ...     print('More')
    ...
    More
    
    12 cho các chức năng và phương pháp. Luôn luôn sử dụng
    >>> x = int(input("Please enter an integer: "))
    Please enter an integer: 42
    >>> if x < 0:
    ...     x = 0
    ...     print('Negative changed to zero')
    ... elif x == 0:
    ...     print('Zero')
    ... elif x == 1:
    ...     print('Single')
    ... else:
    ...     print('More')
    ...
    More
    
    13 làm tên cho đối số phương thức đầu tiên (xem cái nhìn đầu tiên về các lớp để biết thêm về các lớp và phương thức).A First Look at Classes for more on classes and methods).

  • Don Tiết sử dụng các mã hóa ưa thích nếu mã của bạn được sử dụng trong môi trường quốc tế. Python sườn mặc định, UTF-8 hoặc thậm chí ASCII đơn giản hoạt động tốt nhất trong mọi trường hợp.

  • Tương tự như vậy, don lồng sử dụng các ký tự không phải ASCII trong các định danh nếu chỉ có cơ hội nhỏ nhất mà mọi người nói một ngôn ngữ khác sẽ đọc hoặc duy trì mã.

Chú thích

1

Trên thực tế, gọi theo tham chiếu đối tượng sẽ là một mô tả tốt hơn, vì nếu một đối tượng có thể thay đổi được truyền, người gọi sẽ thấy bất kỳ thay đổi nào mà callee thực hiện đối với nó (các mục được chèn vào danh sách).