2020年6月1日月曜日

開発環境

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 4の解答を求めてみる。

コード

#!/usr/bin/env python3

class Nematode:
    def __init__(self, length: float, gender: str, age: int) -> None:
        self.length = length
        self.gender = gender
        self.age = age

    def __repr__(self):
        return f'{self.__class__.__name__}(body_length: ' + \
            f'{self.length}, gender: {self.gender}, age: {self.age})'

    def __str__(self):
        return f'body length: {self.length}mm, gender: {self.gender}, age: {self.age} days'


if __name__ == "__main__":
    nematode = Nematode(1.2, 'hermaphrodite', 10)
    print(nematode)
    print(repr(nematode))

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

% ./sample4.py
body length: 1.2mm, gender: hermaphrodite, age: 10 days
Nematode(body_length: 1.2, gender: hermaphrodite, age: 10)
%

0 コメント:

コメントを投稿