首页 > 解决方案 > 使用子类中定义的变量的父方法

问题描述

在 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};
}

但这不起作用,即只返回基类中分配的空字符串。我没想到它会起作用,但不确定应该如何做。

标签: perloopinheritance

解决方案


我不明白为什么需要它,但有可能,如果你关闭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' }
}

推荐阅读