Python 函数的那些事

作者: quantgalaxy@outlook.com   
blog: https://blog.csdn.net/quant_galaxy  
欢迎交流

1. 前言

Python的函数,和其他编程语言的定义和使用类似,这里先简单总结一下。

1.1 函数的基本定义

  1. 函数( Function )是组织好的,可重复使用的,用来实现单一, 或相关联功能的代码段。
  2. 函数能提高应用的模块性 ,和代码的重复利用率。
  3. 我们已经接触过Python提供的许多内建函数 ,比如print()。
  4. 但你也可以自己创建函数,这被叫做用户自定义函数。

1.2 Python 函数的定义

  1. 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号 ( )。
  2. 任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数。
  3. 函数的第一行语句可以选择性地使用文档字符串用于存放函数说明。
  4. 函数内容以冒 号起始,并且缩进。
  5. return [表达式] 结束函数,选择性地返回一个值给调用方。
  6. 不带表达式的return相当于返回 None。

举例:

def 函数名(参数列表):
    函数体
def hello() :
    print("Hello World!")

hello()

这篇文章,假设你有了python函数的基础,具体会讲一下python函数中特别的地方。

2. Python函数的那些特点

2.1 Python函数式一等函数

这个特点,意味着python的函数,可以被当成正常变量使用:

  1. 可以传递参数给一个函数
  2. 函数的返回值可以是一个函数
  3. 函数可以被赋值给别的变量

原话是:

Elements with the fewest restrictions are said to have first-class status.
Some of the ‘‘rights and privileges’’ of first-class elements are:

  1. They may be named by variables.
  2. They may be passed as arguments to procedures.
  3. They may be returned as the results of procedures.
  4. 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。

2.2 函数可以有自己的属性和方法

def test(x):
  return x

test.fruit = 'apple'

print(test.fruit) # apple

2.3 可以把代码放到return语句之后

一般来说,return之后的语句不会被执行的,但是try-finally例外:

def test():
  try:
    print('apple')
    print('orange')
    return 1
  finally:
    print('pear')

test()

# apple
# orange
# pear

finally语句总是放在最后被执行。

2.4 函数可以通过 __code__ 获取信息

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:获取函数所在的行号

2.5 使用yield做到记录性返回

yield可以和return一样,用作返回语句。
和return返回不同的是,return返回后,下次调用函数,都是从函数的第一行开始执行。
而yield会记录上次执行的位置,第二次调用的时候,会从上次返回的位置继续执行。

def test2():
  yield 1
  yield 2
  yield 3

for i in test2():
  print(i)

# 1
# 2
# 3

每次调用,yield都是从上次结束的位置开始执行,并返回。

2.6 对象中的 __call__

一个类中,如果实现了 __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

2.7 函数参数和返回值的类型提示(Type Hints)

def add(x:int, y:int) -> int:
  return x + y

x: 提示为integer
y: 提示为integer
返回值: 提示为integer

如果我们传入的一个非integer类型的值,函数可以正常执行。
它的主要作用是方便开发,供IDE 和各种开发工具使用,对代码运行不产生影响,运行时会过滤类型信息。
了解参数的类型,可以使得理解和维护代码库变得更加容易。
永远记住你阅读的代码,比你写的代码要多得多。 因此,你应该优化函数以便于阅读。

作者: quantgalaxy@outlook.com   
blog: https://blog.csdn.net/quant_galaxy  
欢迎交流

2.8 *args and **kwargs

函数的参数,可以使用这两个通用参数来进行泛型获取。
*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'}

2.9 函数装饰器(Decorator functions)

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)

3. 作者

作者: quantgalaxy@outlook.com   
blog: https://blog.csdn.net/quant_galaxy  
欢迎交流

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年12月27日
下一篇 2023年12月27日

相关推荐