wbn*_*wbn 8 polymorphism perl6
我有一个Price
封装了一个类的类Int
.我也希望它有Num
和的构造函数Str
.我认为我可以通过制作Price::new
具有各种类型约束的多方法来实现这一点,但这不是我期望的行为.它看起来像Price.new
完全跳过构造函数并直接BUILD
跳过,绕过了构建逻辑.
我知道从其他Perl 6代码中multi method new
可以接受使用.但是,我还没有找到具有不同类型约束的多态构造函数的示例.如何重写此代码以强制它在构造函数中使用转换逻辑?
LIB/Price.pm6
#!/usr/bin/env perl6 -w
use v6;
unit class Price:ver<0.0.1>;
class X::Price::PriceInvalid is Exception {
has $.price;
method message() {
return "Price $!price not valid"
}
}
# Price is stored in cents USD
has $.price;
multi method new(Int $price) {
say "Int constructor";
return self.bless(:$price);
}
multi method new(Num $price) {
say "Num constructor";
return self.new(Int($price * 100));
}
multi method new(Str $price) {
say "String constructor";
$price .= trans(/<-[0..9.]>/ => '');
unless ($price ~~ m/\.\d**2$/) {
die(X::Price::PriceInvalid(:$price));
}
return self.new(Num($price));
}
submethod BUILD(:$!price) { say "Low-level BUILD constructor" }
method toString() {
return sprintf("%.2f", ($!price/100));
}
Run Code Online (Sandbox Code Playgroud)
吨/ price.t
#!/usr/bin/env perl6 -w
use v6;
use Test;
use-ok 'Price', 'Module loads';
use Price;
# test constructor with Int
my Int $priceInt = 12345;
my $priceIntObj = Price.new(price => $priceInt);
is $priceIntObj.toString(), '123.45',
'Price from Int serializes correctly';
# test constructor with Num
my $priceNum = Num.new(123.45);
my $priceNumObj = Price.new(price => $priceNum);
is $priceNumObj.toString(), '123.45',
'Price from Num serializes correctly';
# test constructor with Num (w/ extra precision)
my $priceNumExtra = 123.4567890;
my $priceNumExtraObj = Price.new(price => $priceNumExtra);
is $priceNumExtraObj.toString(), '123.45',
'Price from Num with extra precision serializes correctly';
# test constructor with Str
my $priceStr = '$123.4567890';
my $priceStrObj = Price.new(price => $priceStr);
is $priceStrObj.toString(), '123.45',
'Price from Str serializes correctly';
# test constructor with invalid Str that doesn't parse
my $priceStrInvalid = 'monkey';
throws-like { my $priceStrInvalidObj = Price.new(price => $priceStrInvalid) }, X::Price::PriceInvalid,
'Invalid string does not parse';
done-testing;
Run Code Online (Sandbox Code Playgroud)
输出 PERL6LIB=lib/ perl6 t/price.t
ok 1 - Module loads
Low-level BUILD constructor
ok 2 - Price from Int serializes correctly
Low-level BUILD constructor
not ok 3 - Price from Num serializes correctly
# Failed test 'Price from Num serializes correctly'
# at t/price.t line 18
# expected: '123.45'
# got: '1.23'
Low-level BUILD constructor
not ok 4 - Price from Num with extra precision serializes correctly
# Failed test 'Price from Num with extra precision serializes correctly'
# at t/price.t line 24
# expected: '123.45'
# got: '1.23'
Low-level BUILD constructor
Cannot convert string to number: base-10 number must begin with valid digits or '.' in '?\$123.4567890' (indicated by ?)
in method toString at lib/Price.pm6 (Price) line 39
in block <unit> at t/price.t line 30
Run Code Online (Sandbox Code Playgroud)
new
您编写的所有多方法都采用一个位置参数.
:( Int $ )
:( Num $ )
:( Str $ )
Run Code Online (Sandbox Code Playgroud)
您正在使用命名参数调用new
:( :price($) )
Run Code Online (Sandbox Code Playgroud)
问题是,既然你没有写一个会接受的是,它使用默认new
的是Mu
提供.
如果您不想允许内置new
,您可以编写一个proto
方法来阻止它搜索继承链.
proto method new (|) {*}
Run Code Online (Sandbox Code Playgroud)
如果您愿意,您也可以使用它来确保所有潜在的子类也遵循关于只有一个位置参数的规则.
proto method new ($) {*}
Run Code Online (Sandbox Code Playgroud)
如果要使用命名参数,请使用它们.
multi method new (Int :$price!){…}
Run Code Online (Sandbox Code Playgroud)
您可能想要new
单独使用并使用多子方法BUILD
.
multi submethod BUILD (Int :$!price!) {
say "Int constructor";
}
multi submethod BUILD (Num :$price!) {
say "Num constructor";
$!price = Int($price * 100);
}
multi submethod BUILD (Str :$price!) {
say "String constructor";
$price .= trans(/<-[0..9.]>/ => '');
unless ($price ~~ m/\.\d**2$/) {
die(X::Price::PriceInvalid(:$price));
}
$!price = Int($price * 100);
}
Run Code Online (Sandbox Code Playgroud)
其实我总是乘上输入100
,这样1
将是相同的"1"
和1/1
和1e0
.
我也会将输出除以100得到一只老鼠.
unit class Price:ver<0.0.1>;
class X::Price::PriceInvalid is Exception {
has $.price;
method message() {
return "Price $!price not valid"
}
}
# Price is stored in cents USD
has Int $.price is required;
method price () {
$!price / 100; # return a Rat
}
# Real is all Numeric values except Complex
multi submethod BUILD ( Real :$price ){
$!price = Int($price * 100);
}
multi submethod BUILD ( Str :$price ){
$price .= trans(/<-[0..9.]>/ => '');
unless ($price ~~ m/\.\d**2$/) {
X::Price::PriceInvalid(:$price).throw;
}
$!price = Int($price * 100);
}
method Str() {
return sprintf("%.2f", ($!price/100));
}
Run Code Online (Sandbox Code Playgroud)
这些new
方法被声明为采用位置参数:
multi method new(Int $price) {
say "Int constructor";
return self.bless(:$price);
}
Run Code Online (Sandbox Code Playgroud)
但后来被称为Price.new(price => $priceInt)
,即通过命名参数.因此,由于所有multi
希望获得额外位置论证的候选者都不适用.
最直接的解决方法是更改构造函数调用Price.new($priceInt)
.
另一种选择是将new
方法编写为multi method new(Int :$price) { ... }
,注意到return self.new(Int($price * 100));
需要变得return self.new(price => Int($price * 100));
适合该变化.
关于代码的一些其他各种各样的注释可能会有所帮助:
new
方法通常被覆盖,以改变界面到建筑(如接受位置参数而不是命名的),而BUILD
与TWEAK
用于控制的值是如何被映射到属性.如果您选择让new
方法采用命名参数,那么处理内部的强制登录也可能更好BUILD
.Num
是一个浮点数,Rat
而是一个有理数(存储为整数分子和分母).文字123.4567890
不是Num
,而是一个Rat
.一个Num
文字总是有一个e
指数部分(像123.45e1
).但是,由于这里的问题是处理货币,Rat
实际上是正确的选择,所以我改变代码使用Rat
类型,而不是Num
,并保持文字原样.toString
方法Str
在Perl 6中更自然地命名.类型通过编写具有该类型名称的方法来定义它们如何强制转换为其他内容.调用它将Str
意味着如果Price
实例在字符串中插入,或者与~
前缀运算符一起使用,它将自动被调用.die(X::Price::PriceInvalid(:$price));
应该是die(X::Price::PriceInvalid.new(:$price));
.