2014年11月3日月曜日

開発環境

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) 2-a, b, c.を解いてみる。

14.8(Exercises) 2-a, b, c.

コード(BBEdit)

sample2.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} square km.'.format(
            self.name, self.population, self.area)
    def __repr__(self):
        return "Country('{0}', {1}, {2})".format(
            self.name, self.population, self.area)

class Continent:
    def __init__(self, name, countries):
        self.name = name
        self.countries = countries
    @property
    def total_population(self):
        return sum(map(lambda country: country.population, self.countries))

    def __str__(self):
        return '{0}\n{1}'.format(
            self.name,
            '\n'.join(map(lambda country: str(country), self.countries)))
    
if __name__ == '__main__':
    print('a.')
    canada = Country('Canada', 34482779, 9984670)
    usa = Country('United States of Ameria', 313914040, 9826675)
    mexico = Country('Mexico', 112336538, 1943950)
    countries = [canada, usa, mexico]
    north_america = Continent('North America', countries)
    print(north_america.name)
    for country in north_america.countries:
        print(country)
    print('b.')
    print(north_america.total_population)
    print('c.')
    print(north_america)

入出力結果(Terminal, IPython)

$ ./sample2.py
a.
North America
Canada has a population of 34482779 and is 9984670 square km.
United States of Ameria has a population of 313914040 and is 9826675 square km.
Mexico has a population of 112336538 and is 1943950 square km.
b.
460733357
c.
North America
Canada has a population of 34482779 and is 9984670 square km.
United States of Ameria has a population of 313914040 and is 9826675 square km.
Mexico has a population of 112336538 and is 1943950 square km.
$

0 コメント:

コメントを投稿