開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: Perl
『続・初めてのPerl 改訂版』(Randal L. Schwartz, brian d foy, Tom Phoenix 著、伊藤 直也、田中 慎司、吉川 英興 監訳、株式会社ロングテール/長尾 高弘 訳、オライリー・ジャパン、2006年、ISBN4-87311-305-9)の11章(オブジェクト入門)の11.11(練習問題)2を解いてみる。
その他参考書籍
2.
コード(BBEdit)
sample.pl
#!/usr/bin/env perl
use strict;
use warnings;
use 5.016;
use utf8;
binmode STDOUT, ':utf8';
binmode STDIN, ':utf8';
binmode STDERR, ':utf8';
{ package LivingCreature;
sub speak {
my $class = shift;
if (@_) {
say "a $class goes '@_'";
} else {
say "a $class goes ", $class->sound, "!";
}
}
}
{ package Person;
sub sound { 'hmmmmm' }
our @ISA = qw(LivingCreature);
}
{ package Animal;
our @ISA = qw(LivingCreature);
sub sound {
die '動物のsoundが定義されていない!';
}
sub speak {
my $class = shift;
if (@_) {
warn "ドリトル博士ではないので、動物と話はできません!" if @_;
} else {
$class->SUPER::speak;
}
}
}
{ package Cow;
our @ISA = qw(Animal);
sub sound { 'moooo' }
}
{ package Horse;
our @ISA = qw(Animal);
# sub sound { 'neigh' }
}
{ package Sheep;
our @ISA = qw(Animal);
sub sound { 'baaaah' }
}
{ package Mouse;
our @ISA = qw(Animal);
sub sound { 'squeak' }
sub speak {
my $class = shift;
$class->SUPER::speak;
say "[but you can barely hear it!]";
}
}
Person->speak('Hi');
Person->speak;
Cow->speak;
Cow->speak("Hi");
Horse->speak;
入出力結果(Terminal)
$ ./sample.pl a Person goes 'Hi' a Person goes hmmmmm! a Cow goes moooo! ドリトル博士ではないので、動物と話はできません! at ./sample.pl line 34. 動物のsoundが定義されていない! at ./sample.pl line 29. $
ちなみにpython3.3の場合。
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
## Copyright (C) 2013 by kamimura
#-*- coding: utf-8 -*-
import sys
class LivingCreature:
def speak(self, words=None):
if words:
print("a {0} goes '{1}'".format(
self.__class__.__name__, words))
else:
print('a {0} goes {1}!'.format(
self.__class__.__name__, self.sound()))
class Person(LivingCreature):
def sound(self):
return 'hmmmmm'
class Animal(LivingCreature):
def sound(self):
print('動物のsoundが定義されていない')
sys.exit()
def speak(self, words=None):
if words:
print('ドリトル博士ではないので、動物と話はできません!')
else:
print('a {0} goes {1}!'.format(
self.__class__.__name__, self.sound()))
class Cow(Animal):
def sound(self):
return 'moooo'
class Horse(Animal): pass
# def sound(self):
# return 'neigh'
class Sheep(Animal):
def sound(self):
return 'baaaah'
class Mouse(Animal):
def sound(self):
return 'squeak'
def speak(self):
Animal.speak(self)
print('[but you can barely hear it!]')
animals = {'Animal':Animal, 'Cow': Cow, 'Horse': Horse, 'Sheep': Sheep,
'Mouse': Mouse}
person = Person()
cow = Cow()
horse = Horse()
person.speak('Hi')
person.speak()
cow.speak()
cow.speak('Hi')
horse.speak()
cow.speak('Hi')
入出力結果(Terminal)
$ ./sample.py a Person goes 'Hi' a Person goes hmmmmm! a Cow goes moooo! ドリトル博士ではないので、動物と話はできません! 動物のsoundが定義されていない $
0 コメント:
コメントを投稿