開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
- プログラミング言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のV部(モジュール)のまとめ演習4.(ネストインポート)を解いてみる。
その他参考書籍
4.(ネストインポート)
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- def countLines1(name): with open(name) as f: return len(f.readlines()) def countChars1(name): with open(name) as f: return len(f.read()) def test1(name): for x, y in [("行数",countLines1(name)), ("文字数", countChars1(name))]: print("{0}: {1}".format(x, y)) # 結果的にopen関数を2回呼び出す事になるのをseek関数を使ってファイルの先頭に移動して # open関数の呼び出しを1回だけにするように修正 def countLines2(file): return len(file.readlines()) def countChars2(file): return len(file.read()) def test2(name): with open(name) as f: print(countLines2(f)) f.seek(0) print(countChars2(f)) if __name__ == '__main__': test2('sample.py')
myclient1.py
#!/usr/bin/env python3.3 # -*- coding:utf-8 from sample import *
myclient2.py
#!/usr/bin/env python import sample
入出力結果(Terminal)
$ python Python 3.3.0 (default, Sep 29 2012, 08:16:08) [GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import myclient1 >>> name='sample.py' >>> myclient1.test2(name) 32 697 >>> import myclient2 >>> myclient2.sample.test2(name) 32 697 >>> myclient1.__dict__ {'countChars2': <function countChars2 at 0x10e37b320>, 'countChars1': <function countChars1 at 0x10e37b170>, '__initializing__': False, '__builtins__': {'compile': <built-in function compile>, 'issubclass': <built-in function issubclass>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'MemoryError': <class 'MemoryError'>, 'iter': <built-in function iter>, 'pow': <built-in function pow>, '__debug__': True, 'divmod': <built-in function divmod>, 'IOError': <class 'OSError'>, 'chr': <built-in function chr>, 'FloatingPointError': <class 'FloatingPointError'>, 'True': True, 'all': <built-in function all>, 'OverflowError': <class 'OverflowError'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'OSError': <class 'OSError'>, 'type': <class 'type'>, '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands for supporting Python development. See www.python.org for more information., 'list': <class 'list'>, 'TabError': <class 'TabError'>, 'slice': <class 'slice'>, 'int': <class 'int'>, 'ord': <built-in function ord>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'hasattr': <built-in function hasattr>, 'NotImplemented': NotImplemented, 'BlockingIOError': <class 'BlockingIOError'>, 'AttributeError': <class 'AttributeError'>, 'format': <built-in function format>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FileExistsError': <class 'FileExistsError'>, 'dict': <class 'dict'>, 'TimeoutError': <class 'TimeoutError'>, 'object': <class 'object'>, 'copyright': Copyright (c) 2001-2012 Python Software Foundation. All Rights Reserved. Copyright (c) 2000 BeOpen.com. All Rights Reserved. Copyright (c) 1995-2001 Corporation for National Research Initiatives. All Rights Reserved. Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. All Rights Reserved., 'max': <built-in function max>, 'super': <class 'super'>, 'bytearray': <class 'bytearray'>, 'sum': <built-in function sum>, 'BufferError': <class 'BufferError'>, '__import__': <built-in function __import__>, 'complex': <class 'complex'>, 'hash': <built-in function hash>, 'callable': <built-in function callable>, 'FutureWarning': <class 'FutureWarning'>, 'eval': <built-in function eval>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'staticmethod': <class 'staticmethod'>, 'Exception': <class 'Exception'>, 'min': <built-in function min>, 'ImportWarning': <class 'ImportWarning'>, 'StopIteration': <class 'StopIteration'>, 'LookupError': <class 'LookupError'>, 'False': False, 'map': <class 'map'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'BaseException': <class 'BaseException'>, 'ChildProcessError': <class 'ChildProcessError'>, 'open': <built-in function open>, 'any': <built-in function any>, 'frozenset': <class 'frozenset'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, '__package__': None, 'len': <built-in function len>, 'next': <built-in function next>, 'InterruptedError': <class 'InterruptedError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'RuntimeError': <class 'RuntimeError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'set': <class 'set'>, 'EOFError': <class 'EOFError'>, 'locals': <built-in function locals>, 'abs': <built-in function abs>, 'ResourceWarning': <class 'ResourceWarning'>, 'isinstance': <built-in function isinstance>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'memoryview': <class 'memoryview'>, 'GeneratorExit': <class 'GeneratorExit'>, 'KeyError': <class 'KeyError'>, 'NameError': <class 'NameError'>, 'str': <class 'str'>, 'property': <class 'property'>, 'round': <built-in function round>, 'SyntaxWarning': <class 'SyntaxWarning'>, '__name__': 'builtins', 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'bool': <class 'bool'>, 'UserWarning': <class 'UserWarning'>, 'tuple': <class 'tuple'>, 'bin': <built-in function bin>, 'ArithmeticError': <class 'ArithmeticError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'float': <class 'float'>, 'help': Type help() for interactive help, or help(object) for help about object., 'ImportError': <class 'ImportError'>, 'ascii': <built-in function ascii>, 'id': <built-in function id>, 'PermissionError': <class 'PermissionError'>, 'TypeError': <class 'TypeError'>, 'SystemExit': <class 'SystemExit'>, 'exec': <built-in function exec>, 'setattr': <built-in function setattr>, 'EnvironmentError': <class 'OSError'>, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'oct': <built-in function oct>, 'getattr': <built-in function getattr>, 'ConnectionError': <class 'ConnectionError'>, 'globals': <built-in function globals>, 'print': <built-in function print>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'range': <class 'range'>, 'None': None, 'ValueError': <class 'ValueError'>, 'IndexError': <class 'IndexError'>, 'SyntaxError': <class 'SyntaxError'>, 'AssertionError': <class 'AssertionError'>, 'Ellipsis': Ellipsis, '_': None, '__build_class__': <built-in function __build_class__>, 'bytes': <class 'bytes'>, 'repr': <built-in function repr>, 'SystemError': <class 'SystemError'>, 'delattr': <built-in function delattr>, 'vars': <built-in function vars>, 'BytesWarning': <class 'BytesWarning'>, 'input': <built-in function input>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'ReferenceError': <class 'ReferenceError'>, 'zip': <class 'zip'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'classmethod': <class 'classmethod'>, 'Warning': <class 'Warning'>, 'hex': <built-in function hex>, 'dir': <built-in function dir>, 'license': Type license() to see the full license text, 'enumerate': <class 'enumerate'>, 'sorted': <built-in function sorted>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'filter': <class 'filter'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'reversed': <class 'reversed'>, 'IndentationError': <class 'IndentationError'>}, '__name__': 'myclient1', 'countLines2': <function countLines2 at 0x10e37b290>, '__cached__': './__pycache__/myclient1.cpython-33.pyc', '__loader__': <_frozen_importlib.SourceFileLoader object at 0x10e378490>, 'test1': <function test1 at 0x10e37b200>, 'countLines1': <function countLines1 at 0x10e37b0e0>, '__file__': './myclient1.py', 'test2': <function test2 at 0x10e37b3b0>, '__doc__': None, '__package__': ''} >>> myclient2.__dict__ {'sample': <module 'sample' from './sample.py'>, '__initializing__': False, '__builtins__': {'compile': <built-in function compile>, 'issubclass': <built-in function issubclass>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'MemoryError': <class 'MemoryError'>, 'iter': <built-in function iter>, 'pow': <built-in function pow>, '__debug__': True, 'divmod': <built-in function divmod>, 'IOError': <class 'OSError'>, 'chr': <built-in function chr>, 'FloatingPointError': <class 'FloatingPointError'>, 'True': True, 'all': <built-in function all>, 'OverflowError': <class 'OverflowError'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'OSError': <class 'OSError'>, 'type': <class 'type'>, '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands for supporting Python development. See www.python.org for more information., 'list': <class 'list'>, 'TabError': <class 'TabError'>, 'slice': <class 'slice'>, 'int': <class 'int'>, 'ord': <built-in function ord>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'hasattr': <built-in function hasattr>, 'NotImplemented': NotImplemented, 'BlockingIOError': <class 'BlockingIOError'>, 'AttributeError': <class 'AttributeError'>, 'format': <built-in function format>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FileExistsError': <class 'FileExistsError'>, 'dict': <class 'dict'>, 'TimeoutError': <class 'TimeoutError'>, 'object': <class 'object'>, 'copyright': Copyright (c) 2001-2012 Python Software Foundation. All Rights Reserved. Copyright (c) 2000 BeOpen.com. All Rights Reserved. Copyright (c) 1995-2001 Corporation for National Research Initiatives. All Rights Reserved. Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. All Rights Reserved., 'max': <built-in function max>, 'super': <class 'super'>, 'bytearray': <class 'bytearray'>, 'sum': <built-in function sum>, 'BufferError': <class 'BufferError'>, '__import__': <built-in function __import__>, 'complex': <class 'complex'>, 'hash': <built-in function hash>, 'callable': <built-in function callable>, 'FutureWarning': <class 'FutureWarning'>, 'eval': <built-in function eval>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'staticmethod': <class 'staticmethod'>, 'Exception': <class 'Exception'>, 'min': <built-in function min>, 'ImportWarning': <class 'ImportWarning'>, 'StopIteration': <class 'StopIteration'>, 'LookupError': <class 'LookupError'>, 'False': False, 'map': <class 'map'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'BaseException': <class 'BaseException'>, 'ChildProcessError': <class 'ChildProcessError'>, 'open': <built-in function open>, 'any': <built-in function any>, 'frozenset': <class 'frozenset'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, '__package__': None, 'len': <built-in function len>, 'next': <built-in function next>, 'InterruptedError': <class 'InterruptedError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'RuntimeError': <class 'RuntimeError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'set': <class 'set'>, 'EOFError': <class 'EOFError'>, 'locals': <built-in function locals>, 'abs': <built-in function abs>, 'ResourceWarning': <class 'ResourceWarning'>, 'isinstance': <built-in function isinstance>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'memoryview': <class 'memoryview'>, 'GeneratorExit': <class 'GeneratorExit'>, 'KeyError': <class 'KeyError'>, 'NameError': <class 'NameError'>, 'str': <class 'str'>, 'property': <class 'property'>, 'round': <built-in function round>, 'SyntaxWarning': <class 'SyntaxWarning'>, '__name__': 'builtins', 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'bool': <class 'bool'>, 'UserWarning': <class 'UserWarning'>, 'tuple': <class 'tuple'>, 'bin': <built-in function bin>, 'ArithmeticError': <class 'ArithmeticError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'float': <class 'float'>, 'help': Type help() for interactive help, or help(object) for help about object., 'ImportError': <class 'ImportError'>, 'ascii': <built-in function ascii>, 'id': <built-in function id>, 'PermissionError': <class 'PermissionError'>, 'TypeError': <class 'TypeError'>, 'SystemExit': <class 'SystemExit'>, 'exec': <built-in function exec>, 'setattr': <built-in function setattr>, 'EnvironmentError': <class 'OSError'>, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'oct': <built-in function oct>, 'getattr': <built-in function getattr>, 'ConnectionError': <class 'ConnectionError'>, 'globals': <built-in function globals>, 'print': <built-in function print>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'range': <class 'range'>, 'None': None, 'ValueError': <class 'ValueError'>, 'IndexError': <class 'IndexError'>, 'SyntaxError': <class 'SyntaxError'>, 'AssertionError': <class 'AssertionError'>, 'Ellipsis': Ellipsis, '_': None, '__build_class__': <built-in function __build_class__>, 'bytes': <class 'bytes'>, 'repr': <built-in function repr>, 'SystemError': <class 'SystemError'>, 'delattr': <built-in function delattr>, 'vars': <built-in function vars>, 'BytesWarning': <class 'BytesWarning'>, 'input': <built-in function input>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'ReferenceError': <class 'ReferenceError'>, 'zip': <class 'zip'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'classmethod': <class 'classmethod'>, 'Warning': <class 'Warning'>, 'hex': <built-in function hex>, 'dir': <built-in function dir>, 'license': Type license() to see the full license text, 'enumerate': <class 'enumerate'>, 'sorted': <built-in function sorted>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'filter': <class 'filter'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'reversed': <class 'reversed'>, 'IndentationError': <class 'IndentationError'>}, '__name__': 'myclient2', '__file__': './myclient2.py', '__package__': '', '__cached__': './__pycache__/myclient2.cpython-33.pyc', '__doc__': None, '__loader__': <_frozen_importlib.SourceFileLoader object at 0x10e378690>} >>> quit() $
0 コメント:
コメントを投稿