[Perl]继承

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,529评论 0 23
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 12,879评论 0 6
  • 看不见的眼泪 流下是为谁 看得见的眼泪 流下是心碎 我为我感到不值 为何泪在流 而无人安慰 流下是为谁 我觉得憔悴...
    雪际陸痕阅读 1,688评论 0 2
  • 收拾杂物,偶然发现一个收纳箱里有七八个笔记本。打开一看,原来都是我工作后写的日记。有的是用蓝色墨水写的,都...
    艾亦苏阅读 1,729评论 0 0
  • 比起下午的蛋糕,第二幅似乎更流畅,长线条还是有待练习!
    小样儿依旧阅读 1,283评论 0 1

友情链接更多精彩内容