gpt4 book ai didi

python - 使用 python 装饰器自动替换函数参数默认值?

转载 作者:太空狗 更新时间:2023-10-29 23:55:25 24 4
gpt4 key购买 nike

其实标题并没有准确反射(reflect)我想问的问题。我的目的是这样的:我正在使用 matplotlib 编写一些绘图函数。我有一系列用于不同绘图目的的函数。像 line_plot() 用于线条,bar_plot() 用于条等。例如:

import matplotlib.pyplot as plt
def line_plot(axes=None,x=None,y=None):
if axes==None:
fig=plt.figure()
axes=fig.add_subplot(111)
else:
pass
axes.plot(x,y)

def bar_plot(axes=None,x=None,y=None):
if axes==None:
fig=plt.figure()
axes=fig.add_subplot(111)
else:
pass
axes.bar(left=x,height=y)

但问题是,对于定义的每个函数,我都必须重复这部分代码:

    if axes==None:
fig=plt.figure()
axes=fig.add_subplot(111)
else:
pass

有没有办法像使用装饰器一样,我可以在定义绘图函数之前应用它,它会自动完成代码的重复部分?因此我不必每次都重复它们。

一个可能的选择是像这样定义一个函数:

def check_axes(axes):
if axes==None:
fig=plt.figure()
axes=fig.add_subplot(111)
return axes
else:
return axes

那么例子将是这样的:

import matplotlib.pyplot as plt    
def line_plot(axes=None,x=None,y=None):
axes=check_axes(axes)
axes.plot(x,y)

def bar_plot(axes=None,x=None,y=None):
axes=check_axes(axes)
axes.bar(left=x,height=y)

但是有没有更好/更干净/更 pythonic 的方式?我想我可以使用装饰器但没有弄清楚。任何人都可以提供一些想法吗?

谢谢!!

最佳答案

以下是使用装饰器的方法:

import matplotlib.pyplot as plt    

def check_axes(plot_fn):
def _check_axes_wrapped_plot_fn(axes=None, x=None, y=None):
if not axes:
fig = plt.figure()
axes = fig.add_subplot(111)
return plot_fn(axes, x, y)
else:
return plot_fn(axes, x, y)
return _check_axes_wrapped_plot_fn

@check_axes
def line_plot(axes, x=None, y=None):
axes.plot(x, y)

@check_axes
def bar_plot(axes, x=None, y=None):
axes.bar(left=x, height=y)

工作原理:@check_axes 语法重新定义修饰函数的名称,例如line_plot 是由装饰器创建的新函数,即 _check_axes_wrapped_plot_fn。这个“包装”函数处理检查逻辑,然后调用原始绘图函数。

如果您希望 check_axes 能够装饰任何将 axes 作为其第一个参数的绘图函数,而不仅仅是那些也只采用 xy 参数,你可以使用 Python 的方便 *任意参数列表的语法:

def check_axes(plot_fn):
def _check_axes_wrapped_plot_fn(axes=None, *args):
if not axes:
fig = plt.figure()
axes = fig.add_subplot(111)
return plot_fn(axes, *args) # pass all args after axes
else:
return plot_fn(axes, *args) # pass all args after axes
return _check_axes_wrapped_plot_fn

现在,这是否是“更好/更清洁/更 Pythonic”可能是一个有争议的问题,并且取决于更大的上下文。

顺便说一句,本着“更像 Pythonic”的精神,我重新格式化了您的代码,使其更接近 PEP8时尚指南。注意参数列表中逗号后的空格,= 赋值运算符周围的空格(但当 = 用于函数关键字参数时不是),并且说 not axes 而不是 axes == None

关于python - 使用 python 装饰器自动替换函数参数默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11773755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com