def 的来龙去脉

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了def 的来龙去脉相关的知识,希望对你有一定的参考价值。

kwargs = {‘color‘:‘blue‘,‘price‘:100}
def car(**kw):
    print(kw)

car(**kwargs)  # 向函数中传递参数:字典
{‘color‘: ‘blue‘, ‘price‘: 100}
kwargs = {‘color‘:‘yellow‘,‘user‘:‘coop‘}
def car(color:‘red‘,price=99):
    print(color,price)

car(**kwargs)  #出现此错误的原因是字典中的key与函数中的关键字不一致导致的
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-6-a7900d7bbd3d> in <module>()
      3     print(color,price)
      4 
----> 5 car(**kwargs)

TypeError: car() got an unexpected keyword argument ‘user‘
kwargs = {‘color‘:‘yellow‘,‘price‘:‘coop‘}
def car(color:‘red‘,price=99):
    print(color,price)

car(**kwargs)  # 此处函数car调用的是字典中的key值。
yellow coop
args = (‘yellow‘,‘coop‘)
def car(color:‘red‘,price=99):
    print(color,price)

car(*args)
yellow coop
args = (‘coop‘,‘yellow‘)
def car(color:‘red‘,user=99):   #函数的关键字传递参数。字典传递参数需要满足字典中的key与函数中的关键字一致,元组传参相当于位置传参。
    print(color,user)

car(*args)
coop yellow
def car(price,color=‘blue‘):  #参数可以没有,但如果有的话,就必须给一个值。
    print(price,color)
car(99)
99 blue
def car(color=‘blue‘,*,price):
    print(color,price)
car()
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-16-d7882ea42481> in <module>()
      1 def car(color=‘blue‘,*,price):
      2     print(color,price)
----> 3 car()

TypeError: car() missing 1 required keyword-only argument: ‘price‘
def car(color=‘blue‘,*,price):  #星号*后面的参数必须要给一个值
    print(color,price)
car(99)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-17-aa444378c236> in <module>()
      1 def car(color=‘blue‘,*,price):
      2     print(color,price)
----> 3 car(99)

TypeError: car() missing 1 required keyword-only argument: ‘price‘
def car(color=‘blue‘,*,price):
    print(color,price)
car(price=99)  # 如此才可以price = 99,默认值放在前面了。
blue 99

lambda表达式,匿名函数

def plus(x):
    return  x+1
plus(22)
23
lambda x : x+2  #冒号前是变量,冒号后面是表达式,方法
<function __main__.<lambda>(x)>
add = lambda x :x+22  #不推荐 这种赋值的方式使用lambda
add(22)
44
def all_up(x):
    return x.strip().upper()

all_up(‘python‘)
‘PYTHON‘
all_up_again = lambda x: x.strip().upper()
print(all_up_again)
<function <lambda> at 0x000002730CEB4EA0>
all_up_again = lambda x: x.strip().upper()
all_up_again
<function __main__.<lambda>(x)>
all_up_again(‘hello‘)
‘HELLO‘
# https://www.python.org/dev/peps/pep-0008/#programming-recommendations 函数的推荐的使用方式
my_list = [1,2,3,4,5,6,7,8]
def odd(*L):
    new_list = []
    for i in L:
        if i % 2 == 1:
            new_list.append(i)
    return new_list
odd(my_list)

技术分享图片

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-30-5ba25fc6b1ee> in <module>()
      7             new_list.append(i)
      8     return new_list
----> 9 odd(my_list)

<ipython-input-30-5ba25fc6b1ee> in odd(*L)
      4     new_list = []
      5     for i in L:
----> 6         if i % 2 == 1:
      7             new_list.append(i)
      8     return new_list

TypeError: unsupported operand type(s) for %: ‘list‘ and ‘int‘
# https://www.python.org/dev/peps/pep-0008/#programming-recommendations
my_list = [1,2,3,4,5,6,7,8]  # 列表 ,原来不止元组可以这样,列表,集合也可以的
def odd(*L):
    new_list = []
    for i in L:
        if i % 2 == 1:
            new_list.append(i)
    return new_list
odd(*my_list)
[1, 3, 5, 7]
# https://www.python.org/dev/peps/pep-0008/#programming-recommendations
my_list = {1,2,3,4,5,6,7,8}  # 集合
def odd(*L):
    new_list = []
    for i in L:
        if i % 2 == 1:
            new_list.append(i)
    return new_list
odd(*my_list)  # 不论是集合还是列表,当用这种方式传递参数的时候,都会在内部转换元组。
[1, 3, 5, 7]

filter?

Init signature: filter(self, /, *args, **kwargs)
Docstring:
filter(function or None, iterable) --> filter object

Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
Type: type

filter(lambda x :x%2==1, my_list)
<filter at 0x2730d039278>
list(filter(lambda x :x % 2 == 1,my_list))  # 转换成列表方法
[1, 3, 5, 7]
my_dict = {‘color‘:‘red‘,‘user‘:‘coop‘}
filter(lambda x :x%2==1, my_dict)
<filter at 0x2730d0397b8>
my_dict1 = filter(lambda x :x%2==1, my_dict)

函数注释 和 文档说明

def add(x,y):
    """Add x and y together""" #函数注释
    return x+y
add.__doc__  # 调用函数注释
‘Add x and y together‘
def add(x:int,y:‘随便‘) -> int:  # ->返回的是整数:return:int
    return x + y
add.__doc__
add.__annotations__
{‘x‘: int, ‘y‘: ‘随便‘, ‘return‘: int}
# pass 当函数或者循环中没想好怎么写的时候,可以使用这个pass,替代代码,占位使用
def  add():
    psss

以上是关于def 的来龙去脉的主要内容,如果未能解决你的问题,请参考以下文章

[Grid Layout] Use auto-fill and auto-fit if the number of repeated grid tracks is not to be def(代码片段

Flutter工程代码管理 pubspec.yaml.packages 与 pubspec.lock文件的来龙去脉

Flutter工程代码管理 pubspec.yaml.packages 与 pubspec.lock文件的来龙去脉

第四篇 函数

Alink漫谈 : 模型的来龙去脉

货币的来龙去脉