gpt4 book ai didi

perl - 驼鹿 (Perl) : access attribute definitions in base classes

转载 作者:行者123 更新时间:2023-12-04 11:29:52 24 4
gpt4 key购买 nike

使用 __PACKAGE__->meta->get_attribute('foo') ,您可以访问 foo给定类中的属性定义,这可能很有用。

#!perl
package Bla;
use Moose;
has bla => is => 'ro', isa => 'Str';
has hui => is => 'ro', isa => 'Str', required => 1;
no Moose; __PACKAGE__->meta->make_immutable;

package Blub;
use Moose;
has bla => is => 'ro', isa => 'Str';
has hui => is => 'ro', isa => 'Str', required => 0;
no Moose; __PACKAGE__->meta->make_immutable;

package Blubbel;
use Moose;
extends 'Blub';
no Moose; __PACKAGE__->meta->make_immutable;

package main;
use Test::More;
use Test::Exception;

my $attr = Bla->meta->get_attribute('hui');
is $attr->is_required, 1;

$attr = Blub->meta->get_attribute('hui');
is $attr->is_required, 0;

$attr = Blubbel->meta->get_attribute('hui');
is $attr, undef;
throws_ok { $attr->is_required }
qr/Can't call method "is_required" on an undefined value/;
diag 'Attribute aus Basisklassen werden hier nicht gefunden.';

done_testing;

然而,正如这个小代码示例所证明的那样,这不能用于访问基类中的属性定义,这对于我的特定情况更有用。有没有办法实现我想要的?

最佳答案

NOTE that get_attribute does not search superclasses, for that you need to use find_attribute_by_name



Class::MOP::Class docs .确实这段代码通过了:
my $attr = Bla->meta->find_attribute_by_name('hui');
is $attr->is_required, 1;

$attr = Blub->meta->find_attribute_by_name('hui');
is $attr->is_required, 0;

$attr = Blubbel->meta->find_attribute_by_name('hui');
is $attr->is_required, 0;

关于perl - 驼鹿 (Perl) : access attribute definitions in base classes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6229656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com