題目は「Pythonism」。Pythonらしさ、ということ。それは何かというと結局は「読みやすさ」に尽きるのだという。
自分は新しい言語を習う場合は
- 変数やクラス定義
- フロー制御
無知その(1) __init__でいちいち変数代入を書いていた。
以前の俺
class MyClass(object):
def __init__(self, arg1 = None, arg2 = None):
self.arg1 = arg1
self.arg2 = arg2
if __name__ == '__main__':
mc = MyClass(arg1 = 10, arg2 = 20)
print mc.__dict__
今日からの俺
class MyClass(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
if __name__ == '__main__':
mc = MyClass(arg1 = 10, arg2 = 20)
print mc.__dict__
無知その(2) Loopのelse文を知らなかった。
#!/usr/bin/python
for num in range(1,200): #to iterate between 10 to 20
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print '%d equals %d * %d' % (num,i,j)
break #to move to the next number, the #first FOR
else: # else part of the loop
print num, 'is a prime number'
無知その(3) Decoratorの便利さを知らなかった
import signal
import time
class TimeoutError(Exception):
def __init__(self, value = "Timed Out"):
self.value = value
def __str__(self):
return repr(self.value)
def timeout(seconds_before_timeout):
def decorate(f):
def handler(signum, frame):
raise TimeoutError()
def new_f(*args, **kwargs):
old = signal.signal(signal.SIGALRM, handler)
signal.alarm(seconds_before_timeout)
try:
result = f(*args, **kwargs)
finally:
signal.signal(signal.SIGALRM, old)
signal.alarm(0)
return result
new_f.func_name = f.func_name
return new_f
return decorate
@timeout(5)
def mytest():
print "Start"
for i in range(1,10):
time.sleep(1)
print "%d seconds have passed" % i
if __name__ == '__main__':
try:
mytest()
except TimeoutError:
print "Timout!"
無知その(4) context handler(with)を知らなかった
What’s New in Python 2.6より
from decimal import Decimal, Context, localcontext
# Displays with default precision of 28 digits
v = Decimal('578')
print v.sqrt()
with localcontext(Context(prec=16)):
# All code in this block uses a precision of 16 digits.
# The original context is restored on exiting the block.
print v.sqrt()
これくらいかな。あと、テストをどう書くかというのは結構議論が盛り上がった。
0 件のコメント:
コメントを投稿