When using multiple inheritance in Perl is there a way to indicate which SUPER function to use?

元气小坏坏 提交于 2021-01-28 19:32:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!