为什么子类不继承其父类的常量?
所以我正在处理我的 Moosey 业务,我想在我使用数字的这些地方使用常量可能会很好,以明确这些数字的含义或以防它们稍后发生变化
所以在父类中我添加了标准“使用常量”
package Parent;
use constant {
NO_LEVEL => 0,
MY_LEVEL => 1,
YOUR_LEVEL => 2,
};
package Child;
extends 'Parent';
#just to demonstrate that child can or cannot access the constant
sub printMyLevel{
print MY_LEVEL;
}
,但子类不知道父类中设置的常量!哦!
我猜我必须施展一些驼鹿魔法才能让它正常工作,或者完全是别的东西。我对这个问题的搜索没有得到任何结果=/
So I was going about my Moosey business and I thought hey might be nice to use a constant in these places where I'm using numbers, to make it clear what these numbers mean or in case they change later
So in the parent class I added the standard 'use constant'
package Parent;
use constant {
NO_LEVEL => 0,
MY_LEVEL => 1,
YOUR_LEVEL => 2,
};
package Child;
extends 'Parent';
#just to demonstrate that child can or cannot access the constant
sub printMyLevel{
print MY_LEVEL;
}
but the child class is not aware of the constants set in the parent! doh!
I'm guessing I have to do some Moose magic to get this to work right, or something else entirely. My searching on this issue didnt pull up any results =/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
常量是子例程。
请记住,常量是具有空原型的子例程。
perl
利用这一点在编译期间内联它们。但是,方法调用忽略原型,因此以这种方式访问的可继承常量不会被内联。Constants are subroutines.
Keep in mind that constants are subroutines with an empty prototype.
perl
takes advantage of this to inline them during compilation. However, method calls disregard prototypes, and therefore inheritable constants accessed this way would not be inlined.这实际上在文档中提到过,如果只是顺便说一下:
This is actually mentioned in the documentation, if only in passing:
由于常量是子例程,并且您可以通过将它们作为方法调用来获得继承位已经被覆盖到了,这里有一个不同的旋转。
如果您知道您只在单个文件中工作,则可以使用词法常量来桥接包:
如果您在分配给常量时不需要 Perl 死机,则
our
声明会变得更简单一些(并且可以是my
):您可以恢复常量性质,同时仍然使用简洁的语法,并带有一点魔力:
您当然可以省略
$constant
coderef 和内联魔法:Since the constants are subroutines and you can get inheritance by calling them as methods bit has been covered to death already, here is a different spin on things.
If you know you are only working in a single file, you can use lexical constants to bridge packages:
If you don't need perl to die when assigning to the constant, the
our
declaration gets a bit simpler (and could be amy
):You can bring back the constant nature while still using the terse syntax with a little magic:
You can of course omit the
$constant
coderef and inline the magic:将它们称为方法。
Call them as a method.
继承会影响方法调用 (
$x->m
),句号。Inheritance affects methods calls (
$x->m
), period.