開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python (プログラミング言語)
Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART V.(Modules and Packages)、Test Your Knowledge: Part V Exercises 4(Nested imports)を解いてみる。
その他参考書籍
4(Nested imports)
コード(BBEdit)
mymod.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import sys
def countLines1(name):
with open(name) as f:
count = len(f.readlines())
return count
def countChars1(name):
with open(name) as f:
count = len(f.read())
return count
def test1(name):
return {'lines':countLines1(name), 'chars':countChars1(name)}
def countLines2(file):
return len(file.readlines())
def countChars2(file):
return len(file.read())
def test2(name):
with open(name) as f:
lines = countLines2(f)
f.seek(0)
chars = len(f.read())
return {'lines':lines, 'chars':chars}
if __name__ == '__main__':
try:
name = sys.argv[1]
except:
name = 'mymod.py'
print(test1(name))
print(test2(name))
myclient1.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import mymod
if __name__ == '__main__':
name = 'mymod.py'
for func in [mymod.test1, mymod.test2]:
print(func(nam
myclient2.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
from mymod import *
if __name__ == '__main__':
name = 'mymod.py'
for func in [test1, test2]:
print(func(name))
入出力結果(Terminal)
$ ./myclient1.py
{'lines': 38, 'chars': 767}
{'lines': 38, 'chars': 767}
$ ./myclient2.py
{'chars': 767, 'lines': 38}
{'chars': 767, 'lines': 38}
$
0 コメント:
コメントを投稿