Python.use(better) #Vector: step14 -- def _typeError(self,v1,v2,op):
‖記事一覧‖ Python.use(better)《Python3.1》《改訂版》
def _typeError(self, v1, v2, op):
《著》森こねこ、小粒ちゃん+∞《監修》小泉ひよ子とタマゴ倶楽部
第0版♪2001/03/02 ● 第1版♪2003/05/25 ● 第2版♪2004/06/01 ● 第3版♪2009/02/28
課題を作成する過程を通して「数値演算」の理解を深めます。
※ Python1.5 で作成した例題を、Python3.1 で再構成しました。
事例:コードの解説
class Vector(object): ... def __add__(self, other): if isinstance(other, Vector): s = [e1+e2 for e1,e2 in zip(self, other)] return Vector(*s) else: self._typeError(self, other, "+") def __radd__(self, other): #@: if isinstance(other, Vector): return self+other else: self._typeError(other, self, "+") ## ---------------------------------------- def __sub__(self, other): if isinstance(other, Vector): return self+(-other) else: self._typeError(self, other, "-") def __rsub__(self, other): if isinstance(other, Vector): return self-other else: self._typeError(other, self, "-") ## ---------------------------------------- # TypeError: unsupported operand type(s) for +: 'int' and 'Vector' _error = "unsupported operand type(s) for %s: %r and %r" def _typeError(self, v1, v2, op): s = self._error%(op, self._name(v1), self._name(v2)) raise(TypeError(s)) def _name(self, obj): return obj.__class__.__name__
■ #1: メソッド:__add__
def __add__(self, other): if isinstance(other, Vector): ... else: self._typeError(self, other, "+")
■ #2: メソッド:__radd__
def __radd__(self, other): #@: if isinstance(other, Vector): ... else: self._typeError(other, self, "+")
■ #3: メソッド:__sub__
def __sub__(self, other): if isinstance(other, Vector): ... else: self._typeError(self, other, "-")
事例:モジュールを起動する
■ 全項目を確認する
全ステップの「項目」を確認するには、関数 do を利用します。
$ python -i vector.py >>> do() 0: step00 -- class Vector(object): 1: step01 -- def __init__(self, *args): 2: step02x -- def __add__(v1, v2): 3: step03 -- return Vector(*s) 4: step04 -- def __sub__(v1, v2): 5: step05 -- def __neg__(self): 6: step06 -- def __mul__(v1, v2): 7: step07x -- sum(e1*e2 ...) 8: step08x -- if hasattr(v2, "elements"): 9: step09 -- def __rmul__(self, other): 10: step10 -- def __iter__(self): 11: step11x -- def __radd__(self, other): 12: step12x -- raise(TypeError(s)) 13: step13 -- raise(TypeError(s)) 14: step14 -- def _typeError(self, v1, v2, op): >>>
■ 各項目を実行する
各ステップの「動作」を確認するには、関数 do に実引数を指定します。
>>> do(14) >>> # -------------------------------------------------- step14 >>> v = Vector(); v () >>> v1 = Vector(3,4); v1 (3, 4) >>> v2 = Vector(5,-2); v2 (5, -2) >>> v1+v2 (8, 2) >>> v1-v2 (-2, 6) >>> v2-v1 (2, -6) >>> -v1 (-3, -4) >>> -v2 (-5, 2) >>> v1*v2 7 >>> v2*v1 7 >>> v1*3 (9, 12) >>> v2*(-2) (-10, 4) >>> 3*v1 (9, 12) >>> (-2)*v2 (-10, 4) >>> 2+v1 TypeError: unsupported operand type(s) for +: 'int' and 'Vector' >>> v2+5 TypeError: unsupported operand type(s) for +: 'Vector' and 'int' >>> 2-v1 TypeError: unsupported operand type(s) for -: 'int' and 'Vector' >>> v2-5 TypeError: unsupported operand type(s) for -: 'Vector' and 'int'