Xinxinghe 发布于 2015/05/12 22:02
阅读 321
收藏 0

在python自带模块fileinput中,源代码中定义了个类class FileInput, 这个类有个初始化函数,在模块中定义了函数input,在input函数中新建了个FileInput的实例,然后返回实例。


def input(files=None, inplace=False, backup="", bufsize=0,
          mode="r", openhook=None):
    """Return an instance of the FileInput class, which can be iterated.

    The parameters are passed to the constructor of the FileInput class.
    The returned instance, in addition to being an iterator,
    keeps global state for the functions of this module,.
    global _state
    if _state and _state._file:
        raise RuntimeError("input() already active")
    _state = FileInput(files, inplace, backup, bufsize, mode, openhook)
    return _state

class FileInput:
    """FileInput([files[, inplace[, backup[, bufsize, [, mode[, openhook]]]]]])

    Class FileInput is the implementation of the module; its methods
    filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
    nextfile() and close() correspond to the functions of the same name
    in the module.
    In addition it has a readline() method which returns the next
    input line, and a __getitem__() method which implements the
    sequence behavior. The sequence must be accessed in strictly
    sequential order; random access and readline() cannot be mixed.

    def __init__(self, files=None, inplace=False, backup="", bufsize=0,
                 mode="r", openhook=None):
        if isinstance(files, str):
            files = (files,)
            if files is None:
                files = sys.argv[1:]
            if not files:
                files = ('-',)
                files = tuple(files)
        self._files = files
        self._inplace = inplace
        self._backup = backup
        self._bufsize = bufsize or DEFAULT_BUFSIZE
        self._savestdout = None
        self._output = None
        self._filename = None
        self._lineno = 0
        self._filelineno = 0
        self._file = None
        self._isstdin = False
        self._backupfilename = None
        self._buffer = []
        self._bufindex = 0
        # restrict mode argument to reading modes
        if mode not in ('r', 'rU', 'U', 'rb'):
            raise ValueError("FileInput opening mode must be one of "
                             "'r', 'rU', 'U' and 'rb'")
        if 'U' in mode:
            import warnings
            warnings.warn("'U' mode is deprecated",
                          DeprecationWarning, 2)
        self._mode = mode
        if openhook:
            if inplace:
                raise ValueError("FileInput cannot use an opening hook in inplace mode")
            if not callable(openhook):
                raise ValueError("FileInput openhook must be callable")
        self._openhook = openhook