【问题标题】:Simulate Python like “property” in Perl在 Perl 中像“属性”一样模拟 Python
【发布时间】: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} 会给我“在这里我需要从另一个模块调用方法”。

【问题讨论】:

    标签: python perl


    【解决方案1】:

    $fp->{property} 是哈希查找,而不是方法调用。您正在绕过您的 OO 接口并直接与对象的实现进行交互。要调用您的访问器,请改用$fp->property()

    我不明白您为什么要使用 Class::Accessor 并手动定义 property 方法。做一个或另一个,而不是两个。

    【讨论】:

      【解决方案2】:

      我不完全理解你的问题,但也许下一个会涵盖它:

      #!/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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-27
        • 1970-01-01
        • 1970-01-01
        • 2012-07-24
        • 2016-08-29
        • 2014-03-17
        • 2018-09-21
        相关资源
        最近更新 更多