objects
スクリプト言語の比較
http://hyperpolyglot.org/scripting を参考に、スクリプト言語の勉強をしてまいります。
objects
perl | php | python | ruby | |
---|---|---|---|---|
define class |
package Int; use Moose; has 'value' => ( is => 'rw' ); around BUILDARGS => sub { my $orig = shift; my $class = shift; my $v = $_[0] || 0; $class->$orig(value => $v); }; no Moose;
|
<?php class Int { private $value; function __construct($int=0) { $this->value = $int; } function getValue() { return $this->value; } function setValue($i) { $this->value = $i; } } ?>
|
class Int: def __init__(self, v=0): self.value = v
|
class Int attr_accessor :value def initialize(i=0) @value = i end end
|
create object |
my $i = new Int(); # or my $i = Int->new();
|
<?php $i = new Int(); ?>
|
i = Int()
|
i = Int.new
|
invoke getter, setter |
my $v = $i->value; $i->value($v+1);
|
<?php $v = $i->getValue(); $i->setValue($v+1); ?>
|
v = i.value
i.value = v+1
|
v = i.value
i.value = v+1
|
instance variable accessibility |
|
|
|
|
define method |
# in package: sub plus { my $self = shift; $self->value + $_[0]; }
|
<?php function plus($i) { return $this->value + $i; } ?>
|
def plus(self,v): return self.value + v
|
def plus(i) value + i end
|
invoke method |
$i->plus(7)
|
<?php $i->plus(7) ?>
|
i.plus(7)
|
i.plus(7)
|
destructor |
# in package: sub DEMOLISH { my $self = shift; my $v = $self->value; print "bye, $v\n"; }
|
<?php function __destruct() { echo "bye, $this->value\n"; } ?>
|
def __del__(self): print("bye, %", self.value)
|
val = i.value ObjectSpace.define_finalizer(int) { puts "bye, #{val}" }
|
method missing |
# in package: our $AUTOLOAD; sub AUTOLOAD { my $self = shift; my $argc = scalar(@_); print "no def: $AUTOLOAD" . " arity: $argc\n"; }
|
<?php function __call($name, $args) { $argc = count($args); echo "no def: $name " . "arity: $argc\n"; } ?>
|
def __getattr__(self, name): s = "no def: "+name+" arity: %d" return lambda *a: print(s % len(a))
|
def method_missing(name, *a) puts "no def: #{name}" + " arity: #{a.size}" end
|
inheritance |
package Counter; use Moose; extends 'Int'; my $instances = 0; sub BUILD { $instances += 1; } sub incr { my $self = shift; my $v = $self->value; $self->value($v + 1); } sub instances { $instances; } no Moose;
|
<?php class Counter extends Int { private static $instances = 0; function __construct($int=0) { Counter::$instances += 1; parent::__construct($int); } function incr() { $i = $this->getValue(); $this->setValue($i+1); } static function getInstances() { return $instances; } } ?>
|
class Counter(Int): instances = 0 def __init__(self, v=0): Counter.instances += 1 Int.__init__(self, v) def incr(self): self.value += 1
|
class Counter < Int @@instances = 0 def initialize @@instances += 1 super end def incr self.value += 1 end def self.instances @@instances end end
|
invoke class method |
Counter::instances();
|
<?php Counter::getInstances() ?>
|
Counter.instances
|
Counter.instances
|