0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

perl のオブジェクトと python の class その1.

Last updated at Posted at 2016-12-14

perl と対比させてく。

基本1

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()

基本2

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())

コールバック

もちょっと真面な例に差し替え予定

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()
  • 2系で使いたければコメントをアンコメント
0
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?