perl - 使用子类中定义的变量的父方法
问题描述
在 Python 中,您可以执行以下操作:
class Binance(Exchange):
name = "Binance"
code = "binance"
并且在父类中有
class Exchange:
@classmethod
def get_name(cls):
return cls.name
现在 Perl!
这很可爱。我希望我的 Perl 对象也一样。
package DWDESReader;
use base qw(DWConfigFileReader);
our $type = "DES";
在基类中:
package DWConfigFileReader;
our $type = "";
sub new {
my ($class, %args) = @_;
$args{type} = $type;
return bless {%args}, $class;
}
sub getType {
my ($self) = @_;
return $self->{type};
}
但这不起作用,即只返回基类中分配的空字符串。我没想到它会起作用,但不确定应该如何做。
解决方案
我不明白为什么需要它,但有可能,如果你关闭strict refs
:
#!/usr/bin/perl
use warnings;
use strict;
{ package My::Base;
sub new { bless {}, shift }
our $name = 'Base';
sub get_name {
my ($self) = @_;
my $class = ref $self || $self;
do { no strict 'refs';
${ $class . '::name' }
}
}
}
{ package My::Child;
use parent -norequire => 'My::Base';
our $name = 'Child';
}
my $ch = 'My::Child'->new;
print $ch->get_name, ' ', 'My::Child'->get_name;
但通常,您只需定义一个包含名称的类方法:
{ package My::Base;
sub new { bless {}, shift }
sub name { 'Base' }
sub get_name { shift->name }
}
{ package My::Child;
use parent -norequire => 'My::Base';
sub name { 'Child' }
}
推荐阅读
- c# - 根据谁登录(基于 AD auth)锁定我的应用程序的某些功能
- windows - 尝试从 GitHub 克隆时出现权限被拒绝(公钥)错误
- c++ - 有没有办法在使用 Booth 算法的二进制乘法期间捕获溢出/下溢?
- android - 如何使用 Amazon Voice Service 或 Alexa 对我的应用进行语音查询
- python - 是否有 Python 函数可以根据条件过滤并将二进制值分配给数据集中的列?
- excel - 仅对具有前缀字母的单元格求和
- angular - @angular/service-worker/src/module.d.ts (30,9):“ModuleWithProviders”类型不是通用的
- android - 如何在应用程序运行时连续检查互联网连接
- node.js - 如何修复“未捕获的错误:模块构建失败(来自 ./node_modules/babel-loader/lib/index.js):”
- c# - @Html.DropDownList 如何将默认值设置为 ACTIVE