属性(它是一个类)如何访问它所属的类?

Jim*_*ger 6 attributes class raku

我知道,这是一个令人困惑的标题。但代码应该很清楚:

class A {
    has $.foo = 1;
    # how can I access B::bar from here?
}

class B {
    has $.bar = 2;
    has A $.a;
    submethod TWEAK {
        $!a = A.new;
    }
}

my $b = B.new;
say $b;    # B.new(bar => 2, a => A.new(foo => 1))
say $b.a;  # A.new(foo => 1)
my $test := $b.a;
say $test; # A.new(foo => 1)
Run Code Online (Sandbox Code Playgroud)

鉴于$test,我如何访问 B::bar (与 $test 处于同一“级别”)?

Sci*_*mon 9

就我个人而言,如果我必须这样做,我会声明A可以有一个属性来履行这样的parent角色。HasBar

role HasBar {
    has $.bar = 2;
}

class A {
   has $.foo = 1;
   has HasBar $.parent;
}

class B does HasBar {
    has A $.a;
    submethod TWEAK {
        $!a = A.new( parent => self );
    }
}
Run Code Online (Sandbox Code Playgroud)

属性通常不(也不应该)知道它们是否包含在另一个对象中。因此,如果您希望能够做到这一点,您需要告诉他们连接存在。我更喜欢使用角色来执行此操作,因为只要A容器具有可访问性,您的类就可以成为许多不同事物的属性bar