16章 計算幾何学 (続き2)
発見
def __init__(self, x: float=0.0, y: float=0.0) -> None:
self.x = x
self.y = y
ここでself.x
には型ヒントを付けなくてもfloatにしてくれる
x: float
から推論してくれてるんだな
PEP484によると引数にヒントをつけることが推奨されてるから
変数の方はヒントを省略していきたい
It is recommended but not required that checked functions have annotations for all arguments and the return type.
他のクラスについても進める
Vectorは型エイリアスで表現する
Vector = Point
ちゃんとエイリアスになっているか
$ python3 -i shape.py
>>> print(Point)
<class '__main__.Point'>
>>> print(Vector)
<class '__main__.Point'>
当たり前の結果だけど、エイリアスになっていると考えていいことにしよう
Segment, Line, Circleについても同様に修正
でこれ
typedef vector<Point> Polygon;
直訳するとこうなるはず
from typing import List
Polygon = List[Point]
どういう使い方になるのかな
調べずにまずやってみる
こういうプログラム
mypyは何も言わない
p1 = Point(1, 2)
p2 = Point(2, 3)
p3 = Point(1, 3)
poly = Polygon([p1, p2, p3])
でも実行するとエラー
$ shape.py
Traceback (most recent call last):
File "/Users/takahiro/study/PCAD/shape.py", line 60, in <module>
p = Polygon([p1, p2, p3])
File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/typing.py", line 1880, in __new__
raise TypeError("Type List cannot be instantiated; "
TypeError: Type List cannot be instantiated; use list() instead
こうじゃないとダメなのか
poly = list([p1, p2, p3])
これなら文句は言われない
こういう代入も許される
でもちょっと気持ち悪くない?
poly = list([p1, p2, p3])
poly2: Polygon = poly
型ヒントつけておくのがお作法的にはよさげ?
poly: Polygon = list([p1, p2, p3])
型を推論してくれるのはいいんだけど
どこまで推論してくれてるのかわからないと微妙にもやっとするな
すっきりできる方法ないかな