`

Python function parameter

 
阅读更多

原创转载请注明出处:http://agilestyle.iteye.com/blog/2327771

 

位置参数

# 位置参数
def power(x):
    return x * x


print(power(5))

Note:

对于power(x)函数,参数x就是一个位置参数。 

 

默认参数

# 默认参数
# 设置默认参数时,有几点要注意:
# 1.必选参数在前,默认参数在后,否则Python的解释器会报错
# 2.当函数有多个参数时,把变化大的参数放前面,变化小的参数放后面。变化小的参数就可以作为默认参数。
def power(x, n=2):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s


print(power(5))
print(power(5, 2))
print(power(5, 3))

Console Output


Note: 默认参数有个最大的坑

def add_end(l=[]):
    l.append('keng')
    return l


# [1, 2, 3, 'keng']
print(add_end([1, 2, 3]))
# [4, 5, 6, 'keng']
print(add_end([4, 5, 6]))
# ['keng']
print(add_end())
# ['keng', 'keng']
print(add_end())
# ['keng', 'keng', 'keng']
print(add_end())

Console Output

所以,定义默认参数时,默认参数必须指向不变对象!

要修改上面的例子,可以用None这个不变对象来实现:

def add_end(l=None):
    if l is None:
        l = []
    l.append('not keng')
    return l


# ['not keng']
print(add_end())
# ['not keng']
print(add_end())
# ['not keng']
print(add_end())

Console Output


为什么要设计str、None这样的不变对象呢?因为不变对象一旦创建,对象内部的数据就不能修改,这样就减少了由于修改数据导致的错误。此外,由于对象不变,多任务环境下同时读取对象不需要加锁,同时读一点问题都没有。我们在编写程序时,如果可以设计一个不变对象,那就尽量设计成不变对象。

 

可变参数

可变参数允许传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。

# 可变参数
# 在参数前面加了一个*号
def cal(*numbers):
    sum = 0
    for i in numbers:
        sum = sum + i
    return sum


print(cal(1, 2, 3))
print(cal(1, 2))
print(cal(1))
print(cal())

# *nums表示把nums这个list的所有元素作为可变参数传进去。这种写法相当有用,而且很常见。
nums = [1, 3, 3]
# 7
print(cal(*nums))

Console Output


  

关键字参数

关键字参数允许传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。

# 关键字参数
def person(name, age, **kwargs):
    print('name:', name, 'age:', age, 'other:', kwargs)


print(person('Kobe', 40))
print(person('Kobe', 40, team='Lakers'))
print(person('Kobe', 40, team='Lakers', job='Guard'))

other = {'team': 'Rockets', 'job': 'Forward'}
print(person('Tracy', 40, **other))

Console Output


  

命名关键字参数

和关键字参数**kw不同,命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数

# 命名关键字参数
# 和关键字参数**kw不同,命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数
def person(name, age, *, team, job):
    print(name, age, team, job)


# 命名关键字参数必须传入参数名
print(person('Kobe', 40, team='Lakers', job='Guard'))

Console Output


 

如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了

# 如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了
def person(name, age, *args, team, job):
    print(name, age, args, team, job)


print(person('Kobe', 40, 'The 2nd Greatest in NBA history', team='Lakers', job='Guard'))
print(person('Kobe', 40, team='Lakers', job='Guard'))

Console Output


 

命名关键字参数可以有缺省值,从而简化调用

def person(name, age, *, team='Lakers', job):
    print(name, age, team, job)


print(person('Kobe', 40, job='Guard'))
print(person('Tracy', 40, team='Rockets', job='Forward')

Console Output


 

参数组合

在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用。但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。

# 参数组合
def f1(a, b, c=0, *args, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)


def f2(a, b, c=0, *, d, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)


print(f1(1, 2))
print(f1(1, 2, c=3))
print(f1(1, 2, 3, 'a', 'b'))
print(f1(1, 2, 3, 'a', 'b', x=99))
print(f2(1, 2, d=99, ext=None))

Console Output


 

对于任意函数,都可以通过一个tuple和dict类似func(*args, **kw)的形式调用它,无论它的参数是如何定义的

# 对于任意函数,都可以通过类似func(*args, **kw)的形式调用它,无论它的参数是如何定义的
args = (1, 2, 3, 4)
kw = {'d': 99, 'x': '#'}
# a = 1 b = 2 c = 3 args = (4,) kw = {'x': '#', 'd': 99}
print(f1(*args, **kw))
args = (1, 2, 3)
kw = {'d': 88, 'x': '#'}
# a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}
print(f2(*args, **kw))

 

参考资料

http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431752945034eb82ac80a3e64b9bb4929b16eeed1eb9000

 

 

 

 

  • 大小: 7 KB
  • 大小: 21.9 KB
  • 大小: 6.9 KB
  • 大小: 7.7 KB
  • 大小: 14.9 KB
  • 大小: 5.6 KB
  • 大小: 10.1 KB
  • 大小: 7.9 KB
  • 大小: 13.4 KB
分享到:
评论

相关推荐

    python函数的定义方式.docx

    python函数的定义方式 Python函数的定义方式 Python是一种高级编程语言,它的函数定义方式非常简单,可以让...它的定义方式如下: ``` def function_name(parameter1, parameter2, ...): # 函数体 ``` 其中,param

    Beginning Python (2005).pdf

    Implementing a Search Utility in Python 200 Try It Out: Writing a Test Suite First 201 Try It Out: A General-Purpose Search Framework 203 A More Powerful Python Search 205 Try It Out: Extending ...

    Python Cookbook, 2nd Edition

    Python Cookbook, 2nd Edition By David Ascher, Alex Martelli, Anna Ravenscroft Publisher : O'Reilly Pub Date : March 2005 ISBN : 0-596-00797-3 Pages : 844 Copyright Preface The ...

    Python for Bioinformatics 第二版,最新版

    6.2.2 Function Parameter Options 110 6.2.3 Generators 113 6.3 MODULES AND PACKAGES 114 6.3.1 Using Modules 115 6.3.2 Packages 116 6.3.3 Installing Third-Party Modules 117 6.3.4 Virtualenv: Isolated ...

    Python SWFTools

    • SWFCombine A multi-function tool for inserting SWFs into Wrapper SWFs, contatenating SWFs, stacking SWFs or for basic parameter manipulation (e.g. changing size). • SWFStrings Scans SWFs for text ...

    Python lambda函数基本用法实例分析

    f=lambda [parameter1,parameter2,……]:expression lambda语句中,冒号前是参数,可以有0个或多个,用逗号隔开,冒号右边是返回值。lambda语句构建的其实是一个函数对象。 1》无参数 f=lambda :'python lambda!' >...

    Python中函数的基本定义与调用及内置函数详解

    函数function是python编程核心内容之一,也是比较重要的一块。首先我们要了解Python函数的基本定义: 函数是什么? 函数是可以实现一些特定功能的小方法或是小程序。在Python中有很多内建函数,当然随着学习的深入,...

    run_jnb:参数化(仅限python3)并执行Jupyter笔记本

    run_jnb run_jnb是用于参数化(仅适用于python... >> > possible_parameter ( './Power_function.ipynb' )[ PossibleParameter ( name = 'exponent' , value = 2 , cell_index = 7 ), PossibleParameter ( name = 'np_a

    Python随手笔记(十)——–错误,调试和测试(1)

    错误处理 在预防程序发生运行错误的时候,可以预先设置返回一个错误代码,然后... r = some_function() if r == (-1): return -1 return r def bar(): r = foo() if r==(-1): print('Error') else: pass 一旦

    Python 内置函数complex详解

    英文文档: class complex([real[, imag]])... If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter

    生成QR二维码

    Use the ``make`` shortcut function:: import qrcode img = qrcode.make('Some data here') Advanced Usage -------------- For more control, use the ``QRCode`` class. For example:: import qrcode qr ...

    npp.8.0.Installer.x64.exe

    14. Fix Python Function List not showing functions in some circumstance. 15. Enhance Folder as Workspace performance while adding/removing files in bulk. 16. Add Ada, Fortran, Fortran77 & Haskell in ...

    npp.8.0.portable.x64.7z

    14. Fix Python Function List not showing functions in some circumstance. 15. Enhance Folder as Workspace performance while adding/removing files in bulk. 16. Add Ada, Fortran, Fortran77 & Haskell in ...

    npp.8.0.portable.x64.zip

    14. Fix Python Function List not showing functions in some circumstance. 15. Enhance Folder as Workspace performance while adding/removing files in bulk. 16. Add Ada, Fortran, Fortran77 & Haskell in ...

    模糊神经网络分类器

    ANFIS is a function approximator program. But, the usage of ANFIS for classifications is unfavorable. For example, there are three classes, and labeled as 1, 2 and 3. The ANFIS outputs are not ...

    sqlmap (懂的入)

    function. 昨天晚上实在忍不住,还是看了一些,然后测试了一下。里面的sql语句太过于简单,不过你可以定制。修改为更富在的语句。以绕过注入检测和其他IDS设 备。 稍晚一下,我编译一个dos版本的给你们。 1、...

    Python中这些简单的函数你还不会?

    文章目录定义和调用函数定义函数参数和返回值变量的作用...functionbody:可选参数,语句体调用函数后要执行的功能代码 函数:系统函数、自定义函数 调用函数: 调用函数就是执行函数 系统函数、自定义函数都是用函数名

    浅析C++11新特性的Lambda表达式

    [capture list] (parameter list) -> return type { function body } 可以看到,他有四个组成部分:  1.capture list: 捕获列表  2.parameter list: 参数列表  3.return type: 返回类型  4.function body...

    boost 1.41 中文文档,使用帮助,教程手册

    金庆 python, signals, signals2 zhaohongchao exception, gil luckycat06 interval, math, math/complex number algorithms, math/common_factor, math/octonion, math/quaternion, math/special_functions, ...

    《DeepLearning with Python》读书笔记(一)

    1.什么是深度学习 三张图理解深度学习工作原理 神经网络中每层对输入数据所做的具体操作保存在该层的权重(weight)中,其本质是...这是神经网络损失函数(loss function)的任务,该函数也叫目标函数(objective fun

Global site tag (gtag.js) - Google Analytics