2014年11月5日水曜日

開発環境

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

14.8(Exercises) 3-a, b.

コード(BBEdit)

sample3.py

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

class Student:
    def __init__(self, member, student_number, courses_taken, current_courses):
        self.member = member
        self.student_number = student_number
        self.courses_taken = courses_taken[:]
        self.current_courses = current_courses[:]
    def __str__(self):
        return 'name:{0}\nnumber:{1}\ncourses:{2}\ncurrent course:{3}'.format(
            self.member.name, self.student_number,
            ', '.join(self.courses_taken), ', '.join(self.current_courses))
    def __repr__(self):
        return 'Student({0}, {1}, {2}, {3})'.format(
            self.member, self.student_number, self.current_courses,
            self.current_courses)

class Member:
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Member(name={0})'.format(self.name)


class Faculty:
    def __init__(self, faculty):
        self.faculty = faculty
    def __repr__(self):
        return 'Faculty(faculty={0})'.format(self.faculty)

if __name__ == '__main__':
    member = Member('kamimura')
    student = Student(member, 10, ['course1', 'course2'],
                      ['course3', 'course4'])
    faculty = Faculty('faculty1')
    print('a.')
    print(student)
    print('b.')
    for c in [member, student, faculty]:
        print(c.__class__)
        print(repr(c))
        print(c)

入出力結果(Terminal, IPython)

$ ./sample3.py
a.
name:kamimura
number:10
courses:course1, course2
current course:course3, course4
b.
<class '__main__.Member'>
Member(name=kamimura)
Member(name=kamimura)
<class '__main__.Student'>
Student(Member(name=kamimura), 10, ['course3', 'course4'], ['course3', 'course4'])
name:kamimura
number:10
courses:course1, course2
current course:course3, course4
<class '__main__.Faculty'>
Faculty(faculty=faculty1)
Faculty(faculty=faculty1)
$

0 コメント:

コメントを投稿