An example of defining a simple counter (ʻadd) and inheriting another counter (ʻaddc
)
f.pl
package Foo;
sub new { bless {x => 0}, shift }
sub add { ++ shift->{x} }
1;
package Bar;
use base qw(Foo) ;
sub new { my $r = Foo->new ; $r->{y} = 0 ; bless $r, shift }
sub addc { ++ shift->{y} }
1;
use Data::Dumper ;
my $o = Foo->new ;
printf "Foo add: %s\n", $o->add for 0 .. 1 ;
printf Dumper $o ;
my $p = Bar->new ;
printf "Bar add: %s\n", $p->add ;
printf "Bar addc: %s\n", $p->addc for 0 .. 1 ;
printf Dumper $p ;
python
$ perl f.pl
Foo add: 1
Foo add: 2
$VAR1 = bless( {
'x' => 2
}, 'Foo' );
Bar add: 1
Bar addc: 1
Bar addc: 2
$VAR1 = bless( {
'y' => 2,
'x' => 1
}, 'Bar' );
f.py
class Foo(object):
def __init__(self):
self._x = 0
def add(self):
self._x = self._x + 1
return self._x
class Bar(Foo):
def __init__(self):
super(Bar, self).__init__()
self._y = 0
def addc(self):
self._y = self._y + 1
return self._y
o = Foo()
for i in [0,1]:
print ("Foo add: {0}".format(o.add()))
print (vars(o))
p = Bar()
print ("Bar add: {0}".format(p.add()))
for i in [0,1]:
print ("Bar addc: {0}".format(p.addc()))
print (vars(p))
python
$ python f.py
Foo add: 1
Foo add: 2
{'_x': 2}
Bar add: 1
Bar addc: 1
Bar addc: 2
{'_y': 2, '_x': 1}
If you want to give a method with the same name as the method of the inheritance source (parent, base class), but you also want to access the inheritance source.
An example of using the inheriting counter ʻadd as ʻaddp
and redefining ʻadd` in the inherited one.
perl
package Foo;
sub new{ bless {x => 0}, shift }
sub add{ ++ shift->{x} }
1;
package Bar;
use base qw(Foo) ;
sub new { my $r = Foo->new ; $r->{y} = 0 ; bless $r, shift }
sub add { ++ shift->{y} }
sub addp { shift->SUPER::add }
1;
use Data::Dumper ;
my $o = Foo->new ;
printf "Foo add: %s\n", $o->add for 0 .. 1 ;
printf Dumper $o ;
my $p = Bar->new ;
printf "Bar addp: %s\n", $p->addp ;
printf "Bar add: %s\n", $p->add for 0 .. 1 ;
printf Dumper $p ;
python
class Foo(object):
def __init__(self):
self._x = 0
def add(self):
self._x = self._x + 1
return self._x
class Bar(Foo):
def __init__(self):
super(Bar, self).__init__()
self._y = 0
def add(self):
self._y = self._y + 1
return self._y
def addp(self):
return super(Bar, self).add()
o = Foo()
for i in [0,1]:
print ("Foo add: {0}".format(o.add()))
print (vars(o))
p = Bar()
print ("Bar addp: {0}".format(p.addp()))
for i in [0,1]:
print ("Bar add: {0}".format(p.add()))
print (vars(p))
Recommended Posts