2014-09-30 56 views
0

我對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}會給我「這裏我需要從另一個模塊調用一個方法」。

回答

3

$fp->{property}是一個哈希查找,而不是方法調用。您正在繞過您的OO接口並直接與對象的實現進行交互。要調用您的訪問者,請改爲使用$fp->property()

我不明白爲什麼你使用Class::Accessor並且還要手動定義property方法。做一個或另一個,而不是兩個。

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