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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章