作者: [email protected]
blog: https://blog.csdn.net/quant_galaxy
欢迎交流
Python的函数,和其他编程语言的定义和使用类似,这里先简单总结一下。
举例:
def 函数名(参数列表):
函数体
def hello() :
print("Hello World!")
hello()
这篇文章,假设你有了python函数的基础,具体会讲一下python函数中特别的地方。
这个特点,意味着python的函数,可以被当成正常变量使用:
原话是:
Elements with the fewest restrictions are said to have first-class status.
Some of the ‘‘rights and privileges’’ of first-class elements are:
- They may be named by variables.
- They may be passed as arguments to procedures.
- They may be returned as the results of procedures.
- They may be included in data structures.
def add10(x):
return x + 10
def apply_all(list1, function):
out = []
for i in list1:
out.append(function(i))
return out
print(apply_all([1,2,3,4,5], add10))
# [11, 12, 13, 14, 15]
这个例子中,add10被当成参数传递给了函数apply_all。
def test(x):
return x
test.fruit = 'apple'
print(test.fruit) # apple
一般来说,return之后的语句不会被执行的,但是try-finally例外:
def test():
try:
print('apple')
print('orange')
return 1
finally:
print('pear')
test()
# apple
# orange
# pear
finally语句总是放在最后被执行。
def myfunction(a, b):
return a + b
print(myfunction.__code__.co_argcount) # 2
print(myfunction.__code__.co_name) # myfunction
print(myfunction.__code__.co_varnames) # ('a', 'b')
print(myfunction.__code__.co_firstlineno) # 1
co_argcount: 获取参数数量
co_name: 获取函数名称
co_varnames:获取参数变量名
co_firstlineno:获取函数所在的行号
yield可以和return一样,用作返回语句。
和return返回不同的是,return返回后,下次调用函数,都是从函数的第一行开始执行。
而yield会记录上次执行的位置,第二次调用的时候,会从上次返回的位置继续执行。
def test2():
yield 1
yield 2
yield 3
for i in test2():
print(i)
# 1
# 2
# 3
每次调用,yield都是从上次结束的位置开始执行,并返回。
一个类中,如果实现了 __call__,那么这个类的实例可以当成函数被调用。
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __call__(self):
return 'apple {self.name}'
remy = Dog('remy', 3)
print(remy())
# apple remy
def add(x:int, y:int) -> int:
return x + y
x: 提示为integer
y: 提示为integer
返回值: 提示为integer
如果我们传入的一个非integer类型的值,函数可以正常执行。
它的主要作用是方便开发,供IDE 和各种开发工具使用,对代码运行不产生影响,运行时会过滤类型信息。
了解参数的类型,可以使得理解和维护代码库变得更加容易。
永远记住你阅读的代码,比你写的代码要多得多。 因此,你应该优化函数以便于阅读。
作者: [email protected]
blog: https://blog.csdn.net/quant_galaxy
欢迎交流
函数的参数,可以使用这两个通用参数来进行泛型获取。
*args 允许你获取多个参数,并把所有参数存储为一个tuple元素。
def test(*args):
print(args)
test() # ()
test(1) # (1,)
test(1,2) # (1, 2)
test(1,2,3) # (1, 2, 3)
kwargs允许你获取多个k-v类型的参数,并把所有参数存储为一个dictionary元素。
def test(**kwargs):
print(kwargs)
test() # {}
test(a=1) # {'a':1}
test(a=1, b=2) # {'a':1, 'b':2}
test(a=1, b=2, apple='pie') # {'a':1, 'b':2, 'apple':'pie'}
A decorator is a function that takes a function object as an argument, and returns a function object as a return value.
Decorator 就是这样一个函数:它接受一个函数作为参数,并返回一个函数作为返回值。
@something
def test():
pass
可以具体看装饰器的文章: Python专家编程系列: 2. 装饰器介绍(Python Decorator)
作者: [email protected]
blog: https://blog.csdn.net/quant_galaxy
欢迎交流