我是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}会给我"在这里我需要从另一个模块调用一个方法"回来。
答案 0 :(得分:3)
$fp->{property}
是哈希查找,而不是方法调用。您绕过了OO界面并直接与对象的实现进行交互。要调用您的访问者,请改用$fp->property()
。
我不明白您使用Class::Accessor
的原因以及手动定义property
方法的原因。做其中一个,而不是两个。
答案 1 :(得分:0)
我不完全理解你的问题,但也许下一个问题包括:
#!/usr/bin/env perl
use strict;
use warnings;
package Foo;
use Moose;
#the property is automagically the getter and setter
has 'property' => (is => 'rw', default => 'default value');
package main;
my $s = Foo->new(); #property set to its default
print $s->property, "\n"; #property as "getter"
$s->property("new value"); #property as "setter"
print $s->property, "\n"; #property as "getter"
打印
default value
new value