【发布时间】:2014-10-01 02:35:56
【问题描述】:
我对 perl 还很陌生,我想知道是否有一种方法可以在 perl 中模拟 python 的属性装饰器?谷歌搜索后,我遇到了访问器和属性,但访问器只是提供 getter/setter,我没有找到关于属性的好的文档。我想要的只是有一个变量,当读取调用getter方法并且值来自getter方法时(我不关心我的场景中的setter,但很高兴知道这是否可能是也是模拟的)。
这是 Python 中的属性 getter 的样子:
>>> class PropertyDemo(object):
... @property
... def obj_property(self):
... return "Property as read from getter"
...
>>> pd = PropertyDemo()
>>> pd.obj_property()
>>> pd.obj_property
'Property as read from getter'
这是我(失败的)在 Perl 中做类似事情的尝试:
#!/usr/bin/perl
my $fp = FailedProperty->new;
print "Setting the proprty of fp object\n";
$fp->property("Don't Care");
print "Property read back is: $fp->{property}\n";
BEGIN {
package FailedProperty;
use base qw(Class::Accessor );
use strict;
use warnings;
sub new {
my $class = shift;
my $self = {property => undef};
bless $self, $class;
return $self;
}
FailedProperty->mk_accessors ("property" );
sub property {
my $self = shift;
return "Here I need to call a method from another module";
}
1;
}
1;
运行这个 perl 代码并没有在 perl 对象中设置键的值,而且似乎也没有调用正确的访问器:
perl /tmp/accessors.pl
Setting the proprty of fp object
Property read back is:
我原以为 fp->{property} 会给我“在这里我需要从另一个模块调用方法”。
【问题讨论】: