问题
As per the title, I'm working on an awkward bit of code that makes use of multiple inheritance and requires that the two SUPER
functions both be called. Is there a way of indicating to Perl which of the two parent classes I want to run the function from? Using $self->SUPER::foo($bar);
only runs the first matching function in @ISA
as per the documentation.
The following gives an idea of how the classes are inherited:
[Base Class]
|
----------------------------
| |
[A] [B]
| |
----------------------------
|
[C]
回答1:
Just specify it:
$self->A::foo($bar)
or
$self->B::foo($bar)
You may also want to look at mro.
回答2:
There are a number of options.
If there are always just two candidate superclasses, you can force @ISA
to be searched in both directions, so
$self->SUPER::method;
{
local @ISA = reverse @ISA;
$self->SUPER::method;
}
or if you want to do something cleverer, you can build the names of all the superclasses' methods at runtime:
my ($caller) = (caller(0))[3] =~ /([^:]+)\z/;
for my $super (@ISA) {
my $method = join '::', $super, $caller;
$self->$method if exists &$method;
}
The first line fetches the name of the currently-executing method and strips off the package name information to leave just the bare name. Then it is appended to each package name in @ISA
and the method is called if it exists.
来源:https://stackoverflow.com/questions/15414696/when-using-multiple-inheritance-in-perl-is-there-a-way-to-indicate-which-super-f