Python奇淫技巧第二弹之装13语法(未完待续)

1. 动态导入代码

  • 动态导入模块:使用importlib.import_module,参考Django的动态引入模块

    def import_string(dotted_path):
        """
        Import a dotted module path and return the attribute/class designated by the
        last name in the path. Raise ImportError if the import failed.
        """
        try:
            module_path, class_name = dotted_path.rsplit('.', 1)
        except ValueError as err:
            raise ImportError("%s doesn't look like a module path" % dotted_path) from err
    ​
        module = import_module(module_path)
    ​
        try:
            return getattr(module, class_name) #判断module模块中是否存在class_name属性或者类
        except AttributeError as err:
            raise ImportError('Module "%s" does not define a "%s" attribute/class' % (
                module_path, class_name)
            ) from err
    ​

     

2. 强制关键参数

  • 用法:当我们希望函数的某些参数强制使用关键字参数时,可以将强制关键字参数放到某个*后面就能得到这种效果

    >>> def f(a, b, *, c='x', d='y', e='z'):
    ...     return 'Hello'
    ​
    # To pass the value for c, d, and e you 
    # will need to explicitly pass it as 
    # "key=value" named arguments:
    >>> f(1, 2, 'p', 'q', 'v')
    TypeError: 
    "f() takes 2 positional arguments but 5 were given"
    ​
    >>> f(1, 2, c='p', d='q',e='v')
    'Hello'

     

3. 注册退出函数

  • atexit.register()装饰器:会在Python解释器中注册一个退出函数,也就是说,他会在脚本退出之前请求调用这个特殊函数

4. print函数的end和sep参数

  • print函数的定义
    def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
        """
        print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
        
        Prints the values to a stream, or to sys.stdout by default.
        Optional keyword arguments:
        file:  a file-like object (stream); defaults to the current sys.stdout.
        sep:   string inserted between values, default a space.
        end:   string appended after the last value, default a newline.
        flush: whether to forcibly flush the stream.
        """
        pass

     

  • 参数含义:
  1. sep:分割值与值,默认是一个空格
  2. end:附件到最后一个值,默认是一个新行
  3. file:指定打印的输出位置,默认是sys.stdout
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值