[Perl]继承

作者: Iam老J | 来源:发表于2016-09-29 12:22 被阅读11次

    parent

    package Baz;
    use parent qw(Foo Bar);
    

    is equivalent to:

    package Baz;
    BEGIN {
      require Foo;
      require Bar;
      push @ISA, qw(Foo Bar);
    }
    

    -norequire

    package Foo;
    sub exclaim { "I CAN HAS PERL" }
    package DoesNotLoadFooBar;
    use parent -norequire, 'Foo', 'Bar';
    # will not go looking for Foo.pm or Bar.pm
    

    is equivalent to

    package Foo;
    sub exclaim { "I CAN HAS PERL" }
    package DoesNotLoadFooBar;
    push @DoesNotLoadFooBar::ISA, 'Foo', 'Bar';
    

    This is also helpful for the case where a package lives within a differently named file:

    package MyHash;
    use Tie::Hash;
    use parent -norequire, 'Tie::StdHash';
    
    #This is equivalent to the following code:
     
    package MyHash;
    require Tie::Hash;
    push @ISA, 'Tie::StdHash';
    

    If you want to load a subclass from a file that require would not consider an eligible filename (that is, it does not end in either .pm or .pmc), use the following code:

    package MySecondPlugin;
    require './plugins/custom.plugin'; # contains Plugin::Custom
    use parent -norequire, 'Plugin::Custom';
    

    SUPER

    By default, every base class needs to live in a file of its own. If you want to have a subclass and its parent class in the same file, you can tell parent not to load any modules by using the -norequire switch:

    package A;
    sub new {
      return bless {}, shift;
    }
    sub speak {
      my $self = shift;
      say 'A';
    }
    
    package B;
    use parent -norequire, 'A';
    sub speak {
      my $self = shift;
      $self->SUPER::speak();
      say 'B';
    }
    
    package C;
    use parent -norequire, 'B';
    sub speak {
      my $self = shift;
      $self->SUPER::speak();
      say 'C';
    }
    
    my $c = C->new();
    $c->speak();
    #---------
    In this example, we will get the following output:
    A
    B
    C
    

    This demonstrates how SUPER is resolved. Even though the object is blessed into the C class, the speak() method in the B class can still call SUPER::speak() and expect it to correctly look in the parent class of B (i.e the class the method call is in), not in the parent class of C (i.e. the class the object belongs to).
    There are rare cases where this package-based resolution can be a problem. If you copy a subroutine from one package to another, SUPER resolution will be done based on the original package.

    Summay

    1. A subclass and its parent class can be in the same file.
    2. use parent -norequire, qw (parent) avoid compiling, which causes syntax error in scenario 1.
    3. SUPER:: calls parent 's method of current object

    相关文章

      网友评论

        本文标题:[Perl]继承

        本文链接:https://www.haomeiwen.com/subject/fxikyttx.html