# Use "def" to create new functions
def add(x, y):
print("x is {} and y is {}".format(x, y))
return x + y # Return values with a return statement
以上这个函数对字符串也适用,但是我们不想要字符串,只需要整数相加?
def add(x: int, y: int) -> int:
print("x is {} and y is {}".format(x, y))
return x + y # Return values with a return statement
然而只是方便阅读……自由派python鼓励大家把类型标注上,但是类型不匹配的时候也不会报错
对于list,字典等可变对象,变量像C语言中的指针一样会改变,对于不可变对象则类似于复制传值,外部的变量不会改变
map(func, *iterables) --> map object
Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
从一个迭代器,经过一个函数映射到另一个迭代器
def squared(x):
return x*x
list(map(squared, [1,2,3,4,5,6]))
In [49]: def sqr(x):
...: return x*x
...: map(sqr,range(4))
Out[49]: <map at 0x765d78b17dc0>
range()返回的是一个迭代器类型,也采用laze evaluate策略,map()之后的也是一个lazy策略的迭代器
# You can define functions that take a variable number of
# positional arguments
def varargs(*args):
return args
# You can define functions that take a variable number of
# keyword arguments, as well
def keyword_args(**kwargs):
return kwargs
# You can do both at once, if you like
def all_the_args(*args, **kwargs):
print(args)
print(kwargs)
all_the_args(1, 2, a=3, b=4) prints:
(1, 2)
{"a": 3, "b": 4}
# Use * to expand args (tuples) and use ** to expand kwargs (dictionaries).
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args) # equivalent: all_the_args(1, 2, 3, 4)
all_the_args(**kwargs) # equivalent: all_the_args(a=3, b=4)
all_the_args(*args, **kwargs) # equivalent: all_the_args(1, 2, 3, 4, a=3, b=4)
# Returning multiple values (with tuple assignments)
def swap(x, y):
return y, x # Return multiple values as a tuple without the parenthesis.
# (Note: parenthesis have been excluded but can be included)
返回多个值:在Python中,可以通过返回一个元组来返回多个值。
元组解包:可以使用元组解包将返回的多个值分别赋给不同的变量。
语法灵活性:返回多个值时,可以省略圆括号,但返回值仍然是一个元组。
# global scope
x = 5
def set_x(num):
# local scope begins here
# local var x not the same as global var x
x = num # => 43
print(x) # => 43
def set_global_x(num):
# global indicates that particular var lives in the global scope
global x
print(x) # => 5
x = num # global var x is now set to 6
print(x) # => 6
强行使用全局变量 :在函数体内通过global varable声明全局变量。
map(square, range(6))
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3) # => 13
def outer(x):
def inner(y):
return x + y # inner访问outer的变量x
return inner
closure = outer(10)
print(closure(5)) # 输出15[1,2](@ref)
内部函数可访问外部函数的变量(词法作用域),但外部函数不能直接访问内部函数的变量
内部函数携带外部函数的环境(变量),即使外部函数已执行完毕(如计数器、惰性求值)
def create_avg():
total = 0
count = 0
def avg(n):
nonlocal total, count
total += n
count += 1
return total/count
return avg
avg = create_avg()
avg(3) # => 3.0
avg(5) # (3+5)/2 => 4.0
avg(7) # (8+7)/3 => 5.0