函数

2018-04-02  本文已影响0人  szn好色仙人

函数基础

>>> if True:
    def Fun():
        print('True')
else:
    def Fun():
        print('False')

        
>>> Fun()
True
>>> def Fun() : pass

>>> 'Test' in dir(Fun)
False
>>> Fun.Test = 'Hello Python'
>>> 'Test' in dir(Fun)
True
>>> Fun.Test
'Hello Python'

作用域

>>> import builtins
>>> dir(builtins)

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

>>> v = 0
>>> def Fun():
    global v, v1
    v, v1 = "ab"

    
>>> print(v)
0
>>> print(v1)
Traceback (most recent call last):
  File "<pyshell#39>", line 1, in <module>
    print(v1)
NameError: name 'v1' is not defined
>>> Fun()
>>> print(v, v1)
a b
>>> def Fun():
    value = 1
    def FunTest():
        print(value)
    return FunTest

>>> pFunTest = Fun()
>>> pFunTest()
1

>>> def Fun():
    v = []
    for i in range(0, 5):
        v.append(lambda : print(i))
    return v

>>> v1 = Fun()
>>> for i in range(0, 5):
    v1[i]()

    
4
4
4
4
4
>>> def F1():
    v1 = 1
    def F2():
        v1 += 1
        print(v1)
    F2()

    
>>> F1()
Traceback (most recent call last):
  File "<pyshell#241>", line 1, in <module>
    F1()
  File "<pyshell#240>", line 6, in F1
    F2()
  File "<pyshell#240>", line 4, in F2
    v1 += 1
UnboundLocalError: local variable 'v1' referenced before assignment
>>> def F1():
    v1 = 1
    def F2():
        nonlocal v1
        v1 += 1
        print(v1)
    F2()

    
>>> F1()
2

>>> def F1():
    v = 1
    def F2():
        def F3():
            nonlocal v
            v += 1
            print(v)
        F3()
    F2()

    
>>> F1()
2

参数

>>> def Fun(*a, **b): print(a, b)

>>> Fun(1, 2, 3, x = 1, y = 2, 'c' = 3)
SyntaxError: keyword can't be an expression
>>> Fun(1, 2, 3, x = 1, y = 2, c = 3)
(1, 2, 3) {'y': 2, 'c': 3, 'x': 1}
>>> def Fun(a, b, c, d) : print(a, b, c, d)

>>> Fun(*"abcd")
a b c d
>>> Fun(**{'a':1, 'b':2, 'c':3, 'd':4})
1 2 3 4


>>> def Fun(**a) : print(a)

>>> Fun(**{'a':1, 'b':2, 'c':3, 'd':4})
{'a': 1, 'c': 3, 'd': 4, 'b': 2}


>>> def Fun(a, b = 1, **c):print(a, b, c)

>>> Fun(1, x = 1, y = 2, b = 3)
1 3 {'y': 2, 'x': 1}
>>> def Fun(a, *b, c = 1) : print(a, b, c)

>>> Fun(1, 2)
1 (2,) 1
>>> def Fun(a, *, b = 0, c = 1) : print(a, b, c)

>>> Fun(1)
1 0 1
>>> Fun(1, 2)
Traceback (most recent call last):
  File "<pyshell#358>", line 1, in <module>
    Fun(1, 2)
TypeError: Fun() takes 1 positional argument but 2 were given

函数的高级话题

>>> def Fun(a:'A', b:'B' = 1, c:'Test' = [1]) -> int:
    print(a, b, c)

    
>>> Fun(1, 2)
1 2 [1]
>>> Fun.__annotations__
{'b': 'B', 'c': 'Test', 'return': <class 'int'>, 'a': 'A'}
lambda arg0, arg1...:expression

>>> f = lambda a, b, c : a + b + c
>>> print(f(*"abc"))
abc

>>> f = lambda x : print('True') if x else print('False')
>>> f(0)
False
>>> f(1)
True
>>> f = lambda x : if x : print(x)
SyntaxError: invalid syntax
>>> list(map(lambda x : x * 2, "abc"))
['aa', 'bb', 'cc']
>>> list(map(pow, [1, 2 ,3], [1, 2, 3]))
[1, 4, 27]

>>> list(filter(lambda x : x > 0, [0, 1, 2, -1]))
[1, 2]

>>> from functools import reduce
>>> reduce(lambda x, y : x + y, [1, 2, 3])
6

迭代和解析第二部分

>>> [ord(x) for x in "szn"]
[115, 122, 110]

>>> [x * 2 + y * 2 for x in "abc" if x == "a" for y in "123" if y == '1' or y == "2"]
['aa11', 'aa22']
>>> def Fun():
    for i in range(0, 5):
        print('Fun:', i)
        yield i

        
>>> Fun()
<generator object Fun at 0x00000000036DFAF8>
>>> list(Fun())
Fun: 0
Fun: 1
Fun: 2
Fun: 3
Fun: 4
[0, 1, 2, 3, 4]
>>> def Fun():
    for i in range(0, 5):
        x = yield i
        print(x)

        
>>> G = Fun()
>>> G.send(1024)
Traceback (most recent call last):
  File "<pyshell#46>", line 1, in <module>
    G.send(1024)
TypeError: can't send non-None value to a just-started generator
>>> next(G)
0
>>> G.send(1024)
1024
1
>>> G.send('s')
s
2
>>> next(G)
None
3
>>> next(G)
None
4
>>> next(G)
None
>>> [x * 2 for x in "szn"]
['ss', 'zz', 'nn']
>>> (x * 2 for x in "szn")
<generator object <genexpr> at 0x00000000036E6EE8>
>>> list((x * 2 for x in "szn"))
['ss', 'zz', 'nn']

>>> {x * 2 for x in "szn"}
{'zz', 'nn', 'ss'}
>>> {x : x * 2 for x in "szn"}
{'s': 'ss', 'z': 'zz', 'n': 'nn'}
>>> def Fun():
    for x in "szn":
        yield x

        
>>> G0, G1 = Fun(), Fun()
>>> iter(G) is G
True
>>> it0, it1 = iter(G0), iter(G0)
>>> next(it0)
's'
>>> next(it1)
'z'
>>> next(G1)
's'
>>> G0 is G1
False
>>> import time
>>> time.clock()
9.330551584887492e-07

>>> import time
>>> def Fun():
    nT0 = time.clock()
    time.sleep(0.1)
    return time.clock() - nT0

>>> Fun()
0.09960021696645072
>>> x = 'a'
>>> def Fun():
    print(x)
    x = 1

    
>>> Fun()
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    Fun()
  File "<pyshell#4>", line 2, in Fun
    print(x)
UnboundLocalError: local variable 'x' referenced before assignment

产生上述问题的原因在于被赋值的变量名在函数内部被当做本地变量来对待,而不是仅仅在赋值之后的语句中才被当做本地变量

>>> def Fun(x = []):
    x.append(1)
    print(x)


>>> Fun()
[1]
>>> Fun()
[1, 1]
>>> Fun([2])
[2, 1]
>>> Fun()
[1, 1, 1]
上一篇 下一篇

猜你喜欢

热点阅读