Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

《Python cookbook》读书笔记📒 #4

Open
wbcs opened this issue Oct 24, 2020 · 0 comments
Open

《Python cookbook》读书笔记📒 #4

wbcs opened this issue Oct 24, 2020 · 0 comments
Labels
py python

Comments

@wbcs
Copy link
Owner

wbcs commented Oct 24, 2020

第七章 函数

new

  • *args 必须作为最后一个 位置参数,其后的所有参数都会被所谓关键字参数。**kwargs 必须作为最后一个 参数:
def func(a, b, *args, c, d, **kwargs):
    pass
  • 函数返回多个值,其实就是返回了一个 tuple 而已(实际上创建tuple的不是()而是,
  • mutable 变量赋值默认参数时,应当使用 None ,而不是[], (), {}
  • 协程(感觉像js里的generator):
def fn():
    prev_args = None
    while True:
        args = yield prev_args
        print('args: ', args)
        prev_args = args

var = fn()
next(var)
print(var.send(1))
print(var.send(2))
print(var.send(3))
'''
args:  1
1
args:  2
2
args:  3
3
'''

API

  • functools.partial
  • 获取对应层级(0为当前stack)的 context: sys._getframe(1).f_locals
import sys

def split_callable_and_others():
    locals = sys._getframe(1).f_locals
    callable_locals = {}
    others = {}
    for key, value in locals.items():
        if callable(value):
            callable_locals.update({key: value})
        else:
            others.update({key: value})
    return callable_locals, others

def test():
    def i_am_callable():
        return 'oh yes'

    fuck = 'bitch'
    # ({'i_am_callable': <function test.<locals>.i_am_callable at 0x7ffb2d13b790>}, {'fuck': 'bitch'})
    print(split_callable_and_others())

if __name__ == '__main__':
    test()
  • callable
@wbcs wbcs added the py python label Oct 24, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
py python
Projects
None yet
Development

No branches or pull requests

1 participant