我正在阅读一本关于 perl 的书,到目前为止,我了解 OOP 的概念,直到遇到以下代码:
sub new {
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my $self = {
color => "bay",
legs => 4,
owner => undef,
@_, # Override previous attributes
};
return bless $self, $class;
}
$ed = Horse->new; # A 4-legged bay horse
$stallion = Horse->new(color => "black"); # A 4-legged black horse
我在该代码中看到的是,在new
子例程中传递的任何内容都被视为包名称,它将使用以下代码转换为对象引用:
my $invocant = shift; #this one just get the name of the package which is the argument passed
return bless $self, $class;
- 现在散列的预先声明有什么用(不是空散列)?为什么
@_
在列表的最后一部分提供?做什么的?
接下来是基于上述代码的语句:
当用作实例方法时,此 Horse 构造函数会忽略其调用者的现有属性。您可以创建第二个构造函数,设计为作为实例方法调用,如果设计得当,您可以使用调用对象中的值作为新构造函数的默认值:
我不明白那90%的陈述。
- 什么是实例方法?还是对象方法?你能举个例子吗?
我知道这my $class = ref($invocant) || $invocant;
是对象和实例方法,但我不确定它们有何不同或如何以不同的方式使用它们。
上面提到的“第二个构造函数”是这样的:
$steed = Horse->new(color => "dun");
$foal = $steed->clone(owner => "EquuGen Guild, Ltd.");
sub clone {
my $model = shift;
my $self = $model->new(%$model, @_);
return $self; # Previously blessed by ->new
}
再说一次,我不知道它做了什么。所以任何人都可以为我澄清这一点。