Keep

函数参数 - Python Practive Book

12/20/2017, 12:45:00 AM 4 min read

遇到不清楚的知识点/细节,最好的方式是读官方文档。但是呢,知道你不会去看,下面简单列了下函数参数相关点:

  • 不存在形参1 - 函数主要起到隔离代码块的作用

    # 打印命令行参数
    import sys
    def test():
      print(sys.argv)
    if (__name__ == '__main__'):
      test()
    
  • 存在形参。在函数调用时,需要指定实参2,否则程序报错

    def square(x):
      return x * x
    square(10) # 100. 同内置函数 pow(10, 2)
    
  • 指定参数默认值

    def hello(company = 'Twitter'):
      print('Hello, {company}'.format(company = company))
    
    hello()
    hello('Google')
    
    company = 'Twitter'
    # 默认值可以是变量,使用的是函数定义处变量的值
    def hello(company = company):
      print('Hello, {company}'.format(company = company))
    
    hello()
    hello('Google')
    company = 'Facebook'
    hello() # 'Hello, Twitter'
    
    currentList = list(range(5))
    # 当默认值是引用类型时,自身的改变会引起默认值改变
    def renderList(lists = currentList):
      for item in lists:
        print(item)
    renderList()            # [0, 1, 2, 3, 4]
    currentList.append(5)
    renderList()            # [0, 1, 2, 3, 4, 5]
    
    # 如果不想共享数据,可以定义默认为 None,这样在函数内部初始化
    def render(list = None):
      if list is None:
        list = []
      # ...
    
  • 实际参数使用名称和形式参数名称绑定,绑定后可任意调整实际参数顺序

    def log(a, b):
      print(a, b)
    
    log(a = 'Hello', b = 'Google')  # Hello Google
    log(b = 'Google', a = 'Hello')  # Hello Google
    
  • 支持任意实际参数个数 - 实际参数不使用名称和形式参数绑定情况,约定叫 positional argument

    # 求所有实参的和
    def sumall(*numbers):
      r = 0
      for n in numbers:
        r += n
      return r
    sumall(1, 2, 3, 4, 5, 6)
    # 也可以这样调用,
    # 把 * 理解成展开操作符
    sumall(*range(10))
    
    # 把所有 dict 合并到第一个实参上
    def merge(base, *others):
      for other in others:
        for key, value in other.items():
          base[key] = value
      return base
    merge({ 'a': 1 }, { 'b': 2 }, { 'c': 3 }) # { 'a': 1, 'b': 2, 'c': 3 }
    
  • 支持任意实际参数个数 - 实际参数使用名称和形式参数绑定情况,约定叫 keyword arguments

    # 用 others 来接收其它不确定参数
    # 当然,也可以把函数定义成接收 dict 类型
    def log(name, age, **others):
      print('name: {name}, age: {age}'.format(name = name, age = age))
    log(name = 'xyy', age = 18)
    
    # 通常会这么调用
    person = {
      'name': 'Redky',
      'age': 30,
      'descritption': '程序员'
    }
    log(**person)
    
  • 支持任意实际参数个数 - 混合使用上两种情况

    def log(name, age, *args, description):
      print('name: {name}, age: {age}'.format(name = name, age = age))
    log('xyy', 18, 'f', '170', description = 'wtf')
    
    def log(name, age, *args, **others):
      print('name: {name}, age: {age}'.format(name = name, age = age))
    log('xyy', 18, 'f', '170', description = 'wtf')
    
  • 定义函数时,约定参数数据类型

    def sum(a: int, b: int) -> int:
      print(sum.__annotations__) # {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
      return a + b
    sum(1, 2)
    

Footnotes

  1. 形式参数(形参):函数在定义时,约定的参数。

  2. 实际参数(实参):函数在被调用时,真实传递的参数。

Tag:
Python

@read2025, 生活在北京(北漂),程序员,宅,喜欢动漫。"年轻骑士骑马出城,不曾见过绝望堡下森森骸骨,就以为自己可以快意屠龙拯救公主。"