[tpm] eval oddness

Shaun Fryer sfryer at sourcery.ca
Thu Dec 10 12:42:59 PST 2009


On Thu, Dec 10, 2009 at 10:41 AM, Madison Kelly <linux at alteeve.com> wrote:

> Anywho, I've been re-reading the (sparse) Net::DBus docs and it always
> shows it's constructor using the "super" method. I know that this has to do
> with inheritance, but to be honest, I've never really understood the true
> meaning of this.
>

hi madison,

perhaps this will help you understand a bit more about what SUPER does, and
how inheritance works in perl.

####[ START Foo.pm ]###
{ package Foo;
    sub new { bless {}, shift }
    sub says { print shift()->word, "\n" }
    sub word { 'foo!' }
1 }
{ package Foo::Bar;
    use base qw(Foo);
    sub word { 'bar!' }
1 }
{ package Foo::Bar::Baz;
    use base qw(Foo::Bar);
    sub says {
        my $self = shift;
        print __PACKAGE__, " isa Foo\n" if $self->isa('Foo');
        print 'Foo::Bar says ', $self->SUPER::word, "\n",
            __PACKAGE__, ' says ', $self->word, "\n";
    }
    sub word { 'baz!' }
1 }
####[ END Foo.pm ]###

bash$ perl -MFoo -e 'Foo->new->says'
foo!
bash$ perl -MFoo -e 'Foo::Bar->new->says'
bar!
bash$ perl -MFoo -e 'Foo::Bar::Baz->new->says'
Foo::Bar::Baz isa Foo
Foo::Bar says bar!
Foo::Bar::Baz says baz!
bash$

as a general rule though, it's best to avoid "implementation inheritance"
("use base", "push @ISA", "use parent") as much as humanly possible. if at
all possible it's much better in practice to use "interface inheritance"
["use Module qw( some interfaces to import )"]. inheritance is intrinsic to
OOP, so it's important to understand the design patterns associated with it
and the pros and cons of each.

cheers,
--
Shaun Fryer
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/toronto-pm/attachments/20091210/4d4f67ba/attachment.html>


More information about the toronto-pm mailing list