调用函数时参数发生了什么变化?

时间:2016-11-08 04:49:38

标签: python matplotlib

我正在研究如何在matplotlib

中格式化轴刻度线

http://matplotlib.org/examples/pylab_examples/custom_ticker1.html

该链接显示以下代码

def millions(x, pos):
    'The two args are the value and tick position'
    return '$%1.1fM' % (x*1e-6)

我无法理解x,pos值在使用时发生了什么

formatter = FuncFormatter(millions)

这个概念叫什么?

1 个答案:

答案 0 :(得分:3)

在行中:

formatter = FuncFormatter(millions)

您正在创建FuncFormatter类的实例,该实例正在使用millions函数进行初始化。这是matplotlib作为其api格式刻度的一部分接受的类。在示例中,formatter对象将传递给y轴的set_major_formatter方法,以便使用millions函数格式化刻度。

您可以在matplotlib源代码中看到它的工作原理。该类定义如下:

class FuncFormatter(Formatter):
    """
    User defined function for formatting

    The function should take in two inputs (tick value *x* and position *pos*)
    and return a string
    """
    def __init__(self, func):
        self.func = func

    def __call__(self, x, pos=None):
        'Return the format for tick val *x* at position *pos*'
        return self.func(x, pos)

现在,formatter中存储的对象将具有指向func函数的属性millions。当matplotlib调用您传递的formatter对象时,它会将参数(即由刻度表示的值)传递给millions函数,该函数由{{1}指向}

由于self.func函数仅根据x值而不是位置来格式化标记,因此millions的定义仅包含millions参数作为虚拟占位符。它必须这样做才能在matplotlib格式化滴答时调用pos时不会出现错误。