Skip to content

Instantly share code, notes, and snippets.

@duck8823
Last active November 6, 2016 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duck8823/407cb8504ae53cf3b7bca5323203aaf3 to your computer and use it in GitHub Desktop.
Save duck8823/407cb8504ae53cf3b7bca5323203aaf3 to your computer and use it in GitHub Desktop.
Perl6のコンストラクタと継承
package Animal;
sub new {
my $pkg = shift;
return bless {name => {@_}->{name}}, $pkg;
}
sub name {
my $self = shift;
return $self->{name};
}
1;
package Bird;
our @ISA;
use Animal;
@ISA = qw/Animal/;
sub new {
my $pkg = shift;
my $super = Animal->new(@_);
return bless {%$super, color => {@_}->{color}}, $pkg;
}
sub color {
my $self = shift;
return $self->{color};
}
1;
my class Animal {
has Str $!name;
submethod BUILD(:$!name) {}
method name {
return $!name;
}
}
my class Bird is Animal {
has Str $!color;
submethod BUILD(:$!color) {}
method color {
return $!color;
}
}
my $animal = Animal.new(name => 'foo');
say $animal.name; # foo
my $bird = Bird.new(name => 'bar', color => 'red');
say $bird.name; # bar
say $bird.color; # red
my class Animal {
submethod BUILD {
say 'An Animal';
}
}
my class Bird is Animal {
submethod BUILD {
say 'A Bird';
}
}
Animal.new; # An Animal
Bird.new; # An Animal; A Bird
#!/bin/env perl
use feature qw/say/;
use Animal;
use Bird;
my $animal = Animal->new(name => 'foo');
say $animal->name; # foo
my $bird = Bird->new(name => 'foo', color => 'red');
say $bird->name; # foo
say $bird->color; # red
my class Animal {
method new {
say 'An Animal';
}
}
my class Bird is Animal {
method new {
say 'A Bird';
}
}
Animal.new; # An Animal
Bird.new; # A Bird
my class Animal {
has Str $!name;
method new(:$name) {
my $self = self.bless;
$self!name($name);
return $self;
}
method !name($name) {
$!name = $name;
}
method name {
return $!name;
}
}
my class Bird is Animal {
has Str $!color;
method new(:$color) {
my $self = self.bless;
$self!color($color);
return $self;
}
method !color($color) {
$!color = $color;
}
method color {
return $!color;
}
}
my $animal = Animal.new(name => 'foo');
say $animal.name; # foo
my $bird = Bird.new(name => 'bar', color => 'red');
say $bird.name; # (Str)
say $bird.color; # red
my class Animal {
has Str $!name;
method name {
return $!name;
}
}
my class Bird is Animal {
has Str $!color;
method color {
return $!color;
}
}
my $animal = Animal.new(name => 'foo');
say $animal.name; # (Str)
my $bird = Bird.new(name => 'bar', color => 'red');
say $bird.name; # (Str)
say $bird.color; # (Str)
my class Animal {
has Str $.name;
}
my class Bird is Animal {
has Str $.color;
}
my $animal = Animal.new(name => 'foo');
say $animal.name; # foo
my $bird = Bird.new(name => 'bar', color => 'red');
say $bird.name; # bar
say $bird.color; # red
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment