函数及函数的参数

函数及函数的参数,第1张


内置函数工具-查看函数文档

  • __doc__属性。


  • 内置函数help
import math
print(math.pow.__doc__)
# output: Return x**y (x to the power of y).
import math
print(help(pow))

#  output:
#  Help on built-in function pow in module builtins:
# 
# pow(base, exp, mod=None)
#     Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
#     
#     Some types, such as ints, are able to use a more efficient algorithm when
#     invoked using the three argument form.
# 
# None

函数的参数:位置参数,在传入时位置至关重要。


def test(parm1, parm2):
    print('1st:{0},2nd:{1}'.format(parm1, parm2))


test('python', 'vision')
#  output: 1st:python,2nd:vision


函数的参数:关键字参数

关键字参数最大的优点在于,可以指定默认值。


def test(param1, param2):
    print('1st:{param1},2nd:{param2}'.format(param1=param1, param2=param2))


test(param1='python', param2='vision')
#  output: 1st:python,2nd:vision
test(param2='vision', param1='python')
#  output: 1st:python,2nd:vision

​
def test(parm1='c#', parm2='2019'):
    print('1st:{parm1},2nd:{parm2}'.format(parm1=parm1, parm2=parm2))


test(parm1='python')
#  output: 1st:python,2nd:2019
test(parm2='vision')
#  output: 1st:c#,2nd:vision
test()
#  output: 1st:c#,2nd:2019
​

赋值时带星号*的变量收集多余的

def test(*params):
    print(params)


test('python')
#  output: ('python',)

test('python','vision')
#  output: ('python', 'vision')

test()
#  output: ()

星号不会收集关键字参数

def test(*params, name):
    print('name:{name} and others :'.format(name=name) + str(params))


test('version', name='python')
# output: name:python and others :('version',)

test('version', 'windows', name='python')
# output: name:python and others :('version', 'windows')

test(name='python')
# output: name:python and others :()

test('version', 'windows', 'python')
# output: 
#  Traceback (most recent call last):
#   File "E:\PyCode\Python_Study\LsitDemo.py", line 14, in 
#     test('version', 'windows', 'python')
# TypeError: test() missing 1 required keyword-only argument: 'name'

要收集关键字参数,可使用两个星号。


def test(*params, name, **keywords):
    print('name:{name} , keywords:{keywords} and others :'.format(name=name, keywords=keywords) + str(params))


test('study', 'pyCharm', 'solidWorks', name='python', version=310, os='windows')
# output: name:python , keywords:{'version': 310, 'os': 'windows'} and others :('study', 'pyCharm', 'solidWorks')

test('study', 'pyCharm', 'solidWorks', name='python')
# output: name:python , keywords:{} and others :('study', 'pyCharm', 'solidWorks')

test('study', 'pyCharm', 'solidWorks', version=310, os='windows', name='python')
# output: name:python , keywords:{} and others :()

test('version', 'windows', 'python')
# output:
# Traceback (most recent call last):
#   File "E:\PyCode\Python_Study\LsitDemo.py", line 14, in 
#     test('version', 'windows', 'python')
# TypeError: test() missing 1 required keyword-only argument: 'name'

通过使用运算符**,可将字典中的值分配给关键字参数

def test1(*params, name, **keywords):
    print('name:{name} , keywords:{keywords} and others :'.format(name=name, keywords=keywords) + str(params))


def test2(**keywords):
    print('name:{0} , version:{1} , os:{2}'.format(*keywords.values()))


def test3(**keywords):
    print('name:{0} , version:{1} , os:{2}'.format(*keywords))


dict1 = {'name': 'python', 'version': '310', 'os': 'windows'}
test1(**dict1)
# output: name:python , keywords:{'version': '310', 'os': 'windows'} and others :()

test2(**dict1)
# output: name:python , version:310 , os:windows

test3(**dict1)
# output: name:name , version:version , os:os

如果在定义和调用函数时都使用*或**,将只传递元组或字典。


因此还不如不使用它们,还可省却些麻烦。


def test1(**keywords):
    print(keywords['name'], '\'s version is ', keywords['version'])


def test2(keywords):
    print(keywords['name'], '\'s version is ', keywords['version'])


dict1 = {'name': 'python', 'version': '310'}
test1(**dict1)
# output: python 's version is  310

test2(dict1)
# output: python 's version is  310

只有在定义函数(允许可变数量的参数)或或调用函数时(拆分字典或序列)使用,星号才能发挥作用。



作用域

在函数内使用的变量称为局部变量,只在函数内起作用。


def test(param):
    print(param)
    param = 'in test'
    print(param)


param = 'out test'
test(param)
print(param)
# output: out test
# output: in test
# output: out test

函数可以使用外部变量,但不建议这么做

param2 = 'variables outside the function'


def test(param1):
    print(param1 + ' and ' + param2)


param = 'pass variables'
test(param)
# output: pass variables and variables outside the function

可使用函数来访问全局变量数global

def test(param1):
    global param2
    print(param1 + ' and ' + param2)


param2 = 'variables outside the function'
param = 'pass variables'
test(param)
# output: pass variables and variables outside the function


def test1(param1):
    print(param1 + ' and ' + globals()['param2'])


test1(param)
# output: pass variables and variables outside the function

通常,不能给外部作用域内的变量赋值,但如果一定要这样做,可使用关键字nonlocal

未使用nonlocal关键字

def fist():
    param = 'in first'

    def second():
        param = 'in second'
        print('param in second :', param)

    second()
    print('param in first:', param)


fist()
# output: param in second : in second
# output: param in first: in first

使用nonlocal关键字

def fist():
    param = 'in first'

    def second():
        nonlocal param
        param = 'in second'
        print('param in second :', param)

    second()
    print('param in first:', param)


fist()
# output: param in second : in second
# output: param in first: in second


lambda表达式

Python提供了一种名为lambda表达式的功能

lambda_expr ::=  "lambda" [parameter_list] ":" expression

lambda 表达式(有时称为 lambda 构型)被用于创建匿名函数。


表达式 lambda parameters: expression 会产生一个函数对象 。


该未命名对象的行为类似于用以下方式定义的函数

def (parameters):
    return expression

请注意通过 lambda 表达式创建的函数不能包含语句或标注。


func1 = lambda x: x ** 2
func2 = lambda x, y: x ** y

print(func1(4))
# output: 16
print(func2(3, 4))
# output: 81

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/570449.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存