Content checking some, not all, class attributes

纵然是瞬间 提交于 2021-01-27 03:57:55

问题


I have a class with attributes. I want to check whether some but not all are defined. So:

class A { 
    has $.a is rw;
    has $.b is rw;
    has $.c is rw;
    has $.d is rw;

    method delete { ... }
}

my A $x .= new(:a<hi>, :d<good>);

## later
$x.b = 'there';

## code in which $x.c may or may not be defined.

## now I want to check if the attributes a, b, and c are defined, without
## needing to know about d
my Bool $taint = False;
for <a b c> {
    $taint &&= $x.$_.defined
}

This will cause errors because an object of type A doesn't have a method 'CALL-ME' for type string.

Is there an introspection method that gives me the values of attributes of a class?

$x.^attributes gives me their names and types, but not their values.

I think there must be some way since dd or .perl provide attribute values - I think.


回答1:


Yes, it is called get_value. It needs the object of the attribute passed to it. For example:

class A {
    has $.a = 42;
    has $.b = 666;
}
my $a = A.new;
for $a.^attributes -> $attr {
    say "$attr.name(): $attr.get_value($a)"
}
# $!a: 42
# $!b: 666


来源:https://stackoverflow.com/questions/59520029/content-checking-some-not-all-class-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!