【问题标题】:Why doesn't the walrus operator pass keyword arguments?为什么海象运算符不传递关键字参数?
【发布时间】:2020-08-25 02:26:41
【问题描述】:

为什么海象运算符没有在这段代码中将关键字参数figsize 传递给matplotlib.pyplot.figure

#TODO: visualize whether the index is a valid x_value
fontsize=21
plt.figure(figsize:=(8,8))
plt.scatter(x_values_theory, y_values_theory, label='Theory')
plt.scatter(x_values_experimental, y_values_experimental, label='Experiment')
plt.xlabel('xlabel', fontsize=fontsize)
plt.ylabel('ylabel', fontsize=fontsize)
plt.legend(fontsize=fontsize)
plt.tick_params(labelsize=fontsize)
plt.show()

产量

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-55-94183c23eb8f> in <module>
      1 #TODO: visualize whether the index == df.[time
      2 fontsize=21
----> 3 plt.figure(figsize:=(8,8))
      4 plt.scatter(x_values_theory, y_values_theory, label='Theory')
      5 plt.scatter(x_values_experimental, y_values_experimental, label='Experiment')

/usr/local/lib/python3.8/site-packages/matplotlib/pyplot.py in figure(num, figsize, dpi, facecolor, edgecolor, frameon, FigureClass, clear, **kwargs)
    649             num = allnums[inum]
    650     else:
--> 651         num = int(num)  # crude validation of num argument
    652 
    653     figManager = _pylab_helpers.Gcf.get_fig_manager(num)

TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

【问题讨论】:

  • 为什么呢?这不是关键字参数语法。 = 是您传递关键字参数的方式。

标签: python python-3.x walrus-operator


【解决方案1】:

关键字参数用= 指定,而不是:=。每the PEP

:= 运算符可以直接用在位置函数调用参数中;但是直接在关键字参数中是无效的。

也就是说

plt.figure(figsize:=(8,8))

等价于

figsize = (8,8)
plt.figure(figsize)

因此,如果您使用正确的运算符,您的代码应该可以工作:

plt.figure(figsize=(8,8))

如果您想同时分配和传递关键字参数,则需要编写这两件事,例如:

plt.figure(figsize=(figsize:=(8,8)))

请注意,括号是必需的。

【讨论】:

  • 我觉得我们已经走下坡路了,为什么要写figsize=(figsize:=(8,8)) figsize:=(8,8) 会呢?
  • @TimTyree 不行,正如您在尝试时看到的那样。你是在问为什么 Python 语言没有什么不同?
  • @TimTyree:那么你需要一些尴尬的变通方法来使用:= 传递关键字参数。
  • Python 通常遵循使事物显式而不是隐式的设计。局部变量名称不会自动匹配除它们本身以外的任何东西。如果要将局部变量传递给同名的关键字参数或字典键,则必须同时编写:局部变量名称和键名称。如果它们碰巧是相同的,那么您可以通过将它们都写成相同来表示。因此,当他们添加 := 运算符时,他们没有改变这一点并不让我感到惊讶。
猜你喜欢
  • 2013-06-06
  • 2015-10-23
  • 1970-01-01
  • 2020-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-13
  • 1970-01-01
相关资源
最近更新 更多