python 教程笔记day3

4.7 More on Defining Functions

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

4.7.2 Keyword Arguments

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])

4.7.3 Arbitrary Argument Lists

def concat(*args,sep="/"):
    return sep.join(args)
concat("earth","mars","venus")
'earth/mars/venus'

4.7.4 Unpacking Argument Lists

list(range(3,6))
[3, 4, 5]
args = [3,7]
list(range(*args))
[3, 4, 5, 6]

4.7.5 Lambda Expreesions

def make_incrementor(n):
    return lambda x: x + n
f = make_incrementor(42)
f(0)
42
f(2)
44

pairs = [(1,'one'),(2,'two'),(3,'three'),(4,'four')]
pairs.sort(key=lambda pair:pair[1])
pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]


pairs = [(1,'one'),(2,'two'),(3,'three'),(4,'four')]
pairs.sort(key=lambda pair:pair[0])
pairs
[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

4.7.6 Documentation Strings

def my_function():
    """Do nothing,but document it."""
    
def my_function():
    """Do nothing,but document it.
    
    No, really, it doesn't do anything.
    """
    pass
print(my_function.__doc__)
Do nothing,but document it.
    
    No, really, it doesn't do anything.
    

4.7.7. Function Annotations 函数注释

def f(ham: str, eggs: str = 'eggs') -> str:
   print("Annotations:", f.__annotations__)
   print("Arguments:", ham, eggs)
   return ham + ' and ' + eggs
f('spam')
Annotations: {'ham': , 'eggs': , 'return': }
Arguments: spam eggs
'spam and eggs'

你可能感兴趣的:(python 教程笔记day3)