2012年12月16日日曜日

開発環境

『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のV部(モジュール)まとめ演習3(ネストインポート)を解いてみる。

その他参考書籍

3.

コード(TextWrangler)

sample.py

#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-

def count_lines(name):
    return len(open(name).readlines())

def count_chars(name):
    return len(open(name).read())

def test():
    name = 'sample.py'
    return "行数:{0} 文字数:{1}".format(
      count_lines(name), count_chars(name))

# test関数でのopen関数の呼び出しを2回ではなく1回で済むように修正
def count_lines1(file):
    file.seek(0)
    return len(file.readlines())

def count_chars1(file):
    file.seek(0)
    return len(file.read())

def test1():
    file = open('sample.py')
    return "行数:{0} 文字数:{1}".format(
      count_lines1(file), count_chars1(file))

sample1.py

#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-

import sample

for f in [sample.test, sample.test1]:
    print(f())

sample2.py

#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-

from sample import *

for f in [test, test1]:
    print(f())

入出力結果(Terminal)

$ ./sample1.py
行数:27 文字数:593
行数:27 文字数:593
$ ./sample2.py
行数:27 文字数:593
行数:27 文字数:593
$

0 コメント:

コメントを投稿