https://docs.python.org/3.9/tutorial/index.html

4.7 函数

*可变参数 **关键字参数

  1. *可变参数在前,**关键字参数在后
  2. *可变参数是元祖,**关键字参数是dict
def cheeseshop(kind, *arguments, **keywords):
    print("--do you have any", kind,"?")
    print("--Iam sorry, we are 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")
-- Do you have any Limburger ?
-- I'm sorry, we are all out of Limburger
It is very runny, sir.
It is really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch

限制参数

def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
      -----------    ----------     ----------
        |             |                  |
        |        Positional or keyword   |
        |                                - Keyword only
         -- Positional only

函数文档(字符串)

def myfunc():
    """Do nothing, 
    but document it.    
    """
pass

print(myfunc.__doc__)

函数注解 __annotations__

函数注解语法 可以让你在定义函数的时候对参数和返回值添加注解

def f(ham: str, eggs: str = 'eggs') -> str:
     print("Annotations:", f.__annotations__)

利用函数注解实现参数类型检查 https://mozillazg.com/2016/01/python-function-argument-type-check-base-on-function-annotations.html

Leave a Reply

Close Menu