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

你可能感兴趣的:(Python,python,动态导入代码,强制关键字,print函数参数)