Contraste avec «perl».
perl
package Foo;
sub new { bless { a => pop }, shift }
sub echo { print shift->{a}, "\n" }
1;
Foo->new("foo")->echo ;
python
class Foo(object):
def __init__(self,a):
self.a = a
def echo(self):
print(self.a)
Foo("foo").echo()
perl
package Foo;
sub new { bless {}, shift }
sub add { ++ shift->{c} }
1;
my $c = Foo->new ;
print $c->add . "\n" for 0 .. 9 ;
python
class Foo(object):
def __init__(self):
self.a = 0
def add(self):
self.a = self.a + 1
return self.a
o = Foo()
for i in range(10):
print (o.add())
perl
package Foo;
sub new { bless { c => 10, @_[1..$#_]}, shift }
1;
use Data::Dumper ;
my $obj = Foo->new( d => 10) ;
print Dumper $obj ;
python
class Foo(object):
def __init__(self, **args):
self.__dict__ = { 'c':10 }
self.__dict__.update( args )
o = Foo(d=10)
print (vars(o))
perl
package Foo;
my $s ;
sub new { $s ||= bless {}, shift ; }
sub add { ++ shift->{c} }
1;
my $o = Foo->new ;
my $p = Foo->new ;
print $o . "\n";
print $p . "\n";
print $o->add . "\n";
print $p->add . "\n";
python
class Foo(object):
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = object.__new__(cls)
return cls._instance
def __init__(self):
self._x = 0
def add(self):
self._x = self._x + 1
return self._x
o = Foo()
p = Foo()
print (id(o))
print (id(p))
print (o.add())
print (p.add())
Sera remplacé par un exemple légèrement sérieux
perl
package Foo;
sub new { bless pop, shift ; } ;
sub execute { shift->(pop); }
1;
my $obj = Foo->new( sub { print $_[0] ; } ) ;
$obj->execute( 'foo' ) ;
python
#from __future__ import print_function
class Foo(object):
def __init__(self, f):
self._f = f
def execute(self):
self._f()
o = Foo(lambda : print ('foo'))
o.execute()
Recommended Posts