>> fib(0)>>> print(fib(0))N_python官网语法">
赞
踩
函数体的第一个语句可以(可选的)是字符串文字;这个字符串文字是函数的文档字符串或 docstring。
>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
>>> fib(0)
>>> print(fib(0))
None
def ask_ok(prompt, retries=4, reminder='Please try again!'):
.......
i = 5
def f(arg=i):
print(arg)
i = 6
f()
输出5
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
不想在后续调用之间共享默认值
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
...........
当存在一个形式为 **name 的最后一个形参时,它会接收一个字典
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
def fun(ord,*array,**dict):
print(type(ord))
print(type(array))
print(type(dict))
fun("111","ddddd",x=12,y=13)
输出:
[Running] python -u "d:\project-python\testproject\test.py"
<class 'str'>
<class 'tuple'>
<class 'dict'>
def fun(ord,*array,**dict):
for i in array:
print(i)
for key,value in dict.items():
print(key+":"+value)
#字典输入必须是str不能是int
fun("111","ddddd",x="12",y="13")
def fun(dict): for key,value in dict.items(): print(key+":"+value) print("*"*30) dict={'name':'gege','age':33} fun(dict) 报错,因为python不能知道dict是什么数据类型,所以,必须加**才能判断,同理,fun(dict)也必须加** 修正为 def fun(**dict): for key,value in dict.items(): print(key+":"+value) print("*"*30) dict={'name':'gege','age':33} fun(**dict) **有类似解构的作用 def fun(**dict): for key,value in dict.items(): print(key+":"+value) print("*"*30) dict={'name':'gege','age':33} fun(**({'name':'gege','age':33})) 报错age后的value必须是字符串 修正为 def fun(**dict): for key,value in dict.items(): print(key+":"+value) print("*"*30) dict={'name':'gege','age':33} fun(**({'name':'gege','age':33}))
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
----------- ---------- ----------
| | |
| Positional or keyword |
| - Keyword only
-- Positional only
位置参数 name 和 **kwds 之间由于存在关键字名称 name 而可能产生潜在冲突:
def foo(name, **kwds):
return 'name' in kwds
任何调用都不可能让它返回 True,因为关键字 ‘name’ 将总是绑定到第一个形参
但使用 / (仅限位置参数) 就可能做到,因为它允许 name 作为位置参数,也允许 ‘name’ 作为关键字参数的关键字名称:
def foo(name, /, **kwds):
return 'name' in kwds
>>> foo(1, **{'name': 2})
True
换句话说,仅限位置形参的名称可以在 **kwds 中使用而不产生歧义。
def write_multiple_items(file, separator, *args):
file.write(separator.join(args))
>>> def concat(*args, sep="/"):
... return sep.join(args)
>>> args = [3, 6]
>>> list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]
>>> def parrot(voltage, state='a stiff', action='voom'):
... print("-- This parrot wouldn't", action, end=' ')
... print("if you put", voltage, "volts through it.", end=' ')
... print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
**var后不能跟形参
def jiebao(**var1,var2="defautl",var3="gege"):
print(var1)
print(type(var1))
dict={"name":"gege","age":"33"}
jiebao(**dict)
使用Lambda 表达式创建匿名函数
>>> def make_incrementor(n):
... return lambda x: x + n
...
#不报错,但是输出的是<function lamda.<locals>.<lambda> at 0x0217C348>
#lambda后不能跟大括号
def lamda(x,y):
return lambda x,y:{x+3*y}
print(lamda(12,3))
文档字符串的内容和格式约定
第一行应该是对象目的的简要概述。不应显式声明对象的名称或类型,因为这些可通过其他方式获得。这一行应以大写字母开头,以句点结尾。
如果文档字符串中有更多行,则第二行应为空白。
Python 解析器不会从 Python 中删除多行字符串文字的缩进,文档字符串第一行之后的第一个非空行确定整个文档字符串的缩进量。然后从字符串的所有行的开头剥离与该缩进 “等效” 的空格。 缩进更少的行不应该出现,但是如果它们出现,则应该剥离它们的所有前导空格。 应在转化制表符为空格后测试空格的等效性(通常转化为8个空格)。
函数标注 是关于用户自定义函数中使用的类型的完全可选元数据信息。
函数标注 以字典的形式存放在函数的 annotations 属性中,并且不会影响函数的任何其他部分。 形参标注的定义方式是在形参名称后加上冒号,后面跟一个表达式,该表达式会被求值为标注的值。 返回值标注的定义方式是加上一个组合符号 ->,后面跟一个表达式,该标注位于形参列表和表示 def 语句结束的冒号之间。
>>> def f(ham: str, eggs: str = 'eggs') -> str:
... print("Annotations:", f.__annotations__)
... print("Arguments:", ham, eggs)
... return ham + ' and ' + eggs
...
>>> f('spam')
Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
'spam and eggs'
————Blueicex 2020/07/19 12:25 blueice1980@126.com
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。