在Perl中调用基本构造函数 [英] Calling base constructor in perl
问题描述
从Perl中的类构造函数调用基本构造函数的正确方法是什么?
What is the correct way to call the base constructor from the class constructor in Perl ?
我看过这样的语法:
my $class = shift;
my $a = shift;
my $b = shift;
my $self = $class->SUPER::new($a, $b);
return $self;
这是正确的吗?如果我们有几个父类,该怎么办.例如这样的类:
Is this correct ? What if we have several parent classes. For example a class like this:
package Gamma;
use base Alpha;
use base Beta;
sub new
{
# Call base constructors...
}
1;
推荐答案
这个问题就是为什么有些人建议不要在您的new
方法中做任何有趣的事情.
new
应该创建并返回一个有福的引用,很难使系统对来自不同父类的同一对象进行两次处理.
This problem is why some people recommend not doing anything interesting in your new
method.
new
is expected to create and return a blessed reference, it's hard to make a system that handle doing this twice for the same object from different parent classes.
一个更清洁的选择是拥有一个新方法,该方法仅创建对象并调用可以设置该对象的另一种方法.第二种方法可以以允许调用多个父方法的方式运行.实际上,new
是您的分配器,而另一个方法是您的构造器.
A cleaner option is to have a new method that only creates the object and calls another method that can set up the object. This second method can behave in a way that allows multiple parent methods to be called. Effectively new
is you allocator and this other method is your constructor.
package Mother;
use strict;
use warnings;
sub new {
my ($class, @args) = @_;
my $self = bless {}, $class;
return $self->_init(@args);
}
sub _init {
my ($self, @args) = @_;
# do something
return $self;
}
package Father;
use strict;
use warnings;
sub new {
my ($class, @args) = @_;
my $self = bless {}, $class;
return $self->_init(@args);
}
sub _init {
my ($self, @args) = @_;
# do something else
return $self;
}
package Child;
use strict;
use warnings;
use base qw(Mother Father);
sub _init {
my ($self, @args) = @_;
# do any thing that needs to be done before calling base classes
$self->Mother::_init(@args); # Call Mother::_init explicitly, SUPER::_init would also call Mother::_init
$self->Father::_init(@args); # Call Father::_init explicitly, SUPER::_init would NOT call Father::_init
# do any thing that needs to be done after calling base classes
return $self;
}
关于使用多重继承可能会发现的复杂问题,其他方法都是正确的.您仍然需要知道Father::_init
不会覆盖Mother::_init
所做的任何决定.从那里只会变得更加复杂和难以调试.
Ether is right about the complications your likely to find by using multiple inheritance. You still need to know that Father::_init
won't override any decisions made by Mother::_init
to start with. It will only get more complicated and harder to debug from there.
我第二次推荐 Moose ,它的界面包括更好地分离对象创建和上面的示例中的初始化通常可以正常工作.
I would second the recommendation of Moose, its interface includes a better separation of the object creation and initialization than my example above that usually just works.
这篇关于在Perl中调用基本构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!