在下面的方法定义,什么是*
和**
为做param2
?
def foo(param1, *param2):
def bar(param1, **param2):
Run Code Online (Sandbox Code Playgroud) python syntax parameter-passing variadic-functions argument-unpacking
有没有办法将Python元组扩展为函数 - 作为实际参数?
例如,这里expand()
有魔力:
some_tuple = (1, "foo", "bar")
def myfun(number, str1, str2):
return (number * 2, str1 + str2, str2 + str1)
myfun(expand(some_tuple)) # (2, "foobar", "barfoo")
Run Code Online (Sandbox Code Playgroud)
我知道可以定义myfun
为myfun((a, b, c))
,但当然可能有遗留代码.谢谢
问题如下:
写一个函数撰写这需要两个函数作为参数,我们称他们为Fa
和Fb
,并返回一个函数,Fres
,这意味着从其它功能outdata是INDATA到第一,例如:Fres(x) = Fa(Fb(x))
.运行示例:
>>> def multiply_five(n):
... return n * 5
...
>>> def add_ten(x):
... return x + 10
...
>>> composition = compose(multiply_five, add_ten)
>>> composition(3)
65
>>> another_composition = compose(add_ten, multiply_five)
>>> another_composition(3)
25
Run Code Online (Sandbox Code Playgroud)
所以我理解这一点,如果我发送3函数compose将需要3 + 10 = 13之后将结果发送到乘法函数它会做:13*5女巫是65.这是我到目前为止写的代码:
def multiply_five(n):
return n*5
def add_ten(x):
return x+10
def compose(func1, func2):
def comp(arg):
return func2(arg)
return func1(comp(arg))
Run Code Online (Sandbox Code Playgroud)
我得到编译错误,我尝试了一些不同的方法:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module> …
Run Code Online (Sandbox Code Playgroud) 在Python中,我们可以为变量赋值.例如,math.sine函数:
sin = math.sin
rad = math.radians
print sin(rad(my_number_in_degrees))
Run Code Online (Sandbox Code Playgroud)
有没有简单的方法为变量分配多个函数(即函数的函数)?例如:
sin = math.sin(math.radians) # I cannot use this with brackets
print sin (my_number_in_degrees)
Run Code Online (Sandbox Code Playgroud)