ด้วยฟังก์ชัน f
ที่เรียกใช้ฟังก์ชันอื่นที่รู้จักกันดีใน Python (เช่น ฟังก์ชัน matplotlib
) วิธีใดคือวิธี pythonic/มีประสิทธิภาพ/หรูหราที่สุดในการกำหนดค่าเริ่มต้นบางส่วน ในขณะที่ยังคงให้ความเป็นไปได้แก่ผู้ใช้ f
ในการปรับแต่งฟังก์ชันที่เรียกใช้อย่างเต็มที่ (โดยทั่วไปจะใช้ **kwargs
) รวมถึงการเขียนทับอาร์กิวเมนต์คำหลักเริ่มต้นที่กำหนดใน f
?
import numpy as np
import matplotlib.pyplot as plt
v = np.linspace(-10.,10.,100)
x,y = np.meshgrid(v, v)
z = -np.hypot(x, y)
def f(ax, n=12, **kwargs):
ax.contourf(x, y, z, n, cmap=plt.cm.autumn, **kwargs)
fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2)
f(ax0) # OK
f(ax1, n=100) # OK
f(ax2, n=100, **{'vmax': -2, 'alpha': 0.2}) # OK
# f(ax3, n=100, **{'cmap': plt.cm.cool}) # ERROR
plt.show()
ที่นี่การโทรครั้งสุดท้ายไปที่ f
พ่น:
TypeError: Contourf () มีหลายค่าสำหรับอาร์กิวเมนต์คำหลัก 'cmap'