2020年6月5日金曜日

開発環境

Practical Programming: An Introduction to Computer Science Using Python 3.6 (Paul Gries(著)、Jennifer Campbell(著)、Jason Montojo(著)、Pragmatic Bookshelf)のChapter 14(Object-Oriented Programming)、Exercise 5の解答を求めてみる。

コード

#!/usr/bin/env python3
from unittest import TestCase, main


class TestLineSegment(TestCase):
    def setUp(self):
        self.segment = LineSegment(Point(1, 1), Point(3, 2))

    def test_slope(self):
        self.assertEqual(self.segment.slope(), 0.5)

    def test_length(self):
        self.assertEqual(self.segment.length(), 2.23606797749979)


class Point:
    def __init__(self, x: float, y: float) -> None:
        self.x = x
        self.y = y


class LineSegment:
    def __init__(self, point1: Point, point2: Point) -> None:
        self.point1 = point1
        self.point2 = point2

    def slope(self) -> float:
        return (self.point2.y - self.point1.y) / \
            (self.point2.x - self.point1.x)

    def length(self) -> float:
        return ((self.point2.x - self.point1.x) ** 2 +
                (self.point2.y - self.point1.y) ** 2) ** (1 / 2)


if __name__ == "__main__":
    main()

入出力結果(Zsh、PowerShell、Terminal、Jupyter(IPython))

% ./sample5.py 
E
======================================================================
ERROR: test_slope (__main__.TestLineSegment)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./sample5.py", line 7, in setUp
    self.segment = LineSegment(Point(1, 1), Point(3, 2))
TypeError: Point() takes no arguments

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
% ./sample5.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
% ./sample5.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
% ./sample5.py -v
test_length (__main__.TestLineSegment) ... ok
test_slope (__main__.TestLineSegment) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
% mypy sample5.py 
Success: no issues found in 1 source file
% 

0 コメント:

コメントを投稿