2014年11月2日日曜日

開発環境

Practical Programming: An Introduction to Computer Science Using Python 3 (Pragmatic Programmers) (Paul Gries (著)、Jennifer Campbell (著)、Jason Montojo (著)、Lynn Beighley (編集)、Pragmatic Bookshelf)のChapter 14(Object-Oriented Programming)、14.8(Exercises) 1-a, b, c, d, e.を解いてみる。

14.8(Exercises) 1-a, b, c, d, e.

コード(BBEdit)

sample1.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class Country:
    def __init__(self, name, population, area):
        self.name = name
        self.population = population
        self.area = area
    def isLarger(self, other):
        return self.area > other.area
    @property
    def population_density(self):
        return self.population / self.area
    def __str__(self):
        return '{0} has a population of {1} and is {2}'.format(
            self.name, self.population, self.area)
    def __repr__(self):
        return "Country('{0}', {1}, {2})".format(
            self.name, self.population, self.area)

if __name__ == '__main__':
    print('a.')
    canada = Country('Canada', 34482779, 9984670)
    print(canada.name)
    print(canada.population)
    print(canada.area)
    print('b.')
    usa = Country('United States of Ameria', 313914040, 9826675)
    print(canada.isLarger(usa))
    print('c.')
    print(canada.population_density)
    print('d.')
    print(usa)
    print('e.')
    print(repr(canada))
    print(repr([canada]))

入出力結果(Terminal, IPython)

$ ./sample1.py
a.
Canada
34482779
9984670
b.
True
c.
3.4535722262227995
d.
United States of Ameria has a population of 313914040 and is 9826675
e.
Country('Canada', 34482779, 9984670)
[Country('Canada', 34482779, 9984670)]
$

0 コメント:

コメントを投稿