有这个示例代码 – 2个包扩展了Some包并重新定义了func方法.
use 5.014; use warnings; package Some { use Moose; use warnings; sub func { say 'func from Some'; } } package Over { use Moose; use warnings; extends 'Some'; override 'func' => sub { say 'func from Over'; }; } package Plain { use Moose; use warnings; extends 'Some'; sub func { say 'func from Plain'; }; } #main for my $package ( qw(Some Over Plain) ) { my $instance = $package->new(); $instance->func; }
runnig代码给出:
func from Some func from Over func from Plain
例如在两种情况下都重新定义了func方法,没有任何警告等.
问题:
>这两种方式之间有一些有意义的差异吗?
>什么时候我应该使用覆盖和什么时候重新定义?
>这是在一些文档中讨论的吗?
解决方法
documentation完美地回答了这个问题.
override ($name,&sub)
An override method is a way of explicitly saying “I am overriding this method from my superclass”. You can call
super
within this method,and it will work as expected. The same thing can be accomplished with a normal method call and theSUPER::
pseudo-package; it is really your choice.