我對Perl很新,我想知道是否有辦法在perl中模擬Python的屬性裝飾器?谷歌搜索後,我遇到了訪問者和屬性,但訪問者只是提供getter/setter,我沒有找到好的文檔屬性。我想要的只是有一個變量,這是讀取調用getter方法的調用並且該值來自getter方法(我不關心我的場景中的setter,但很高興知道這是否可能是也模擬)。像Perl中的「property」一樣模擬Python
下面是屬性的getter看起來像在Python:
>>> 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}會給我「這裏我需要從另一個模塊調用一個方法」。