Python Perl 5面向对象编程

Python Perl 5面向对象编程,python,perl,Python,Perl,我正在尝试将以下python程序移植到perl5: import numpy as np class Hensuu: def __init__(self, data): self.data = data class Kansuu: def __call__(self, input): x = input.data y = x ** 2 output = Hensuu(y) return out

我正在尝试将以下python程序移植到perl5:

import numpy as np


class Hensuu:
    def __init__(self, data):
        self.data = data


class Kansuu:
    def __call__(self, input):
        x = input.data
        y = x ** 2
        output = Hensuu(y)
        return output

x = Hensuu(np.array(9.0))
f = Kansuu()
y = f(x)

print(type(y))
print(y.data)

81 亨苏下午

package Hensuu;
use strict;
use warnings FATAL => 'all';
our $version = 1.0.0;
sub new {
    our ($class,$data) = @_;
    my $self = {data=>$data};
    bless $self,$class;
    return $self;
}
1;

步骤1.pl

#!perl
use strict;
use warnings FATAL => 'all';
use Hensuu;
use PDL;
use PDL::Matrix;
my $datas = mpdl [[1.0,2.0],[3.0,4.0]];
my $x = Hensuu->new($datas);
print($x=>$datas);

坎苏下午

package Kansuu;
#use strict;
use warnings FATAL => 'all';
use Hensuu;
sub call {
    my ($self,$input) = @_;
    my $x = {$input => $data};
    #print($x);
    my $y = $x ** 2;
    my $output = Hensuu->new($y);
    return($output);
}
1;

步骤2.pl

#!perl
#use strict;
use warnings FATAL => 'all';
use PDL;
use PDL::Matrix;
use Hensuu;
use Kansuu;

my $a = mpdl [9.0];
my $x = Hensuu->new($a);
#my $f = Kansuu;
#my $y = $f->call($x);
my $y = Kansuu->call($x);
print($x=>$a);
print(ref($y));
print($y);

发射(步骤2.pl)


上述程序(step2.pl), 我想用打印($y)将显示器设置为“81”;,但我不能。 环境是Windows10Pro,草莓perl PDL版(5.32.1.1), IDE是intellij idea社区版perl插件(2020.3)。

Hensuu.pm:

package-Hensuu;
严格使用;
使用警告;
次新{
我的($class$data)=@;
返回{data=>$data},$class
}
子数据{
我的($self)=@;
返回$self->{data}
}
1.
Kansuu.pm:

packansuu;
严格使用;
使用警告;
使用Hensuu;
副呼叫{
我的($input)=@;
我的$x=$input->data;
我的$y=$x**2;
我的$output=Hensuu->new($y);
返回$output->data
}
1.
步骤2.pl:

#!perl
严格使用;
使用警告;
使用特征qw{say};
使用PDL;
使用PDL::矩阵;
使用Hensuu;
使用Kansuu;
我的$p=mpdl[9.0];
我的$x=Hensuu->new($p);
我的$y=Kansuu::call($x);
比如说$y;
  • 不要将
    我们的
    变量用于不需要全局的事情
  • 不要将
    $a
    用作词法变量,它是在中使用的特殊变量
  • 低级Perl OO不会为属性创建访问器,您需要自己实现它们(请参阅或了解更高级的方法)
  • Kansuu不是一个OO类,请使用完全限定的子例程而不是方法

如果您想在perl中使用现代OOP,请查看Moose或MooRe“Kansuu不是OO类,请使用完全限定的子例程而不是方法”,静态类没有问题<代码>子调用{my($self,$input)=@;…}和
Kansuu->call($x)
很好。(但你的选择也是如此。)@ikegami:是的,但是如果没有实例和类属性,我倾向于不包括OO(类似于Occam的剃刀)。另外,我会使用
$class
而不是
$self
作为类方法。关于“Occam的剃刀”,Kansuu::call并不比Kansuu->call简单(这不是Occam的剃刀的意思)。关于“我会使用$class而不是$self作为类方法”,同上。
Hensuu=HASH(0x1faf80)
[
 [9]
]
HensuuHensuu=HASH(0x25b71c0)
Process finished with exit code 0