[英]Python - Functional inheritance - changing keyword arguments
Is it possible to have a function defined with certain keyword arguments, and then to make a reference to the same function, but using different keyword argument values. 是否可以使用某些关键字参数定义一个函数,然后引用相同的函数,但使用不同的关键字参数值。
eg I have the following 例如我有以下
def f_beta(x,a=2.7,b=3.05):
"""The un-normalised beta distribution function."""
return math.pow(x, a - 1.0)*math.pow(1.0 - x, b - 1.0)
and I would like to do something equivalent to: 我想做的事等同于:
f = f_beta
g = f_beta(a=1.0, b=10.0)
where f
is a copy of the initial function, and g
is the same function but with different default values for the keyword arguments. 其中, f
是初始函数的副本, g
是相同的函数,但关键字参数的默认值不同。 Is there a way to do this for g
without having to build f_beta
this into a class, and without having to re-write various functions. 有没有一种方法可以为g
执行此操作,而不必将f_beta
将此构建到一个类中,而不必重新编写各种函数。
Motivation: I created a class which has a member function init_dist
, which at some point I define in the __init__()
via: 动机:我创建了一个具有成员函数init_dist
的类,该类init_dist
在__init__()
通过以下方式定义:
self.init_dist = f_beta
and would like to be able to pass in a new function. 并希望能够传递新功能。
I have looked at at the following: 我看了以下内容:
and have had no luck in finding any answers, or where I should look for references. 并且没有找到任何答案的运气,或者我应该在哪里寻找参考。
Use functools.partial : 使用functools.partial :
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from functools import partial
>>> import math
>>> def f_beta(x,a=2.7,b=3.05):
... """The un-normalised beta distribution function."""
... return math.pow(x, a - 1.0)*math.pow(1.0 - x, b - 1.0)
...
>>> f = f_beta
>>> g = partial(f_beta, a=1.0, b=10.0)
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f_beta() takes at least 1 argument (0 given)
>>> g()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f_beta() takes at least 1 argument (2 given)
>>> g(13)
-5159780352.0
>>> f(13, 1.0, 10.0)
-5159780352.0
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.