属性值在 Proxy.new (Raku) 中变成“方法”

Jus*_*Guy 6 methods proxy attributes raku

我试图理解为什么属性值是 Proxy.new 之外的 Str(或其他),但成为 Proxy.new 内部的 Method。我把我的代码归结为:

#!/usr/bin/env raku

class Foo does Associative {
  has Str $.string;

  multi method AT-KEY (::?CLASS:D: Str $key) is rw {
    say "\nOutside of Proxy: { $!string.raku }";
    say "Outside of Proxy: { $!string.^name }";

    Proxy.new(
      FETCH => method () {
        say "FETCH: { $!string.raku }";
        say "FETCH: { $!string.^name }";
      },
      STORE => method ($value) {
        say "STORE: { $!string.raku }";
        say "STORE: { $!string.^name }";
      }
    );
  }
}

my $string = 'foobar';

my %foo := Foo.new: :$string;
%foo<bar> = 'baz';
say %foo<bar>;
Run Code Online (Sandbox Code Playgroud)

这是输出:

$ ./proxy.raku 

Outside of Proxy: "foobar"
Outside of Proxy: Str
STORE: method <anon> (Mu: *%_) { #`(Method|94229743999472) ... }
STORE: Method

Outside of Proxy: "foobar"
Outside of Proxy: Str
FETCH: method <anon> (Mu: *%_) { #`(Method|94229743999616) ... }
FETCH: Method
FETCH: method <anon> (Mu: *%_) { #`(Method|94229743999616) ... }
FETCH: Method
FETCH: method <anon> (Mu: *%_) { #`(Method|94229743999616) ... }
FETCH: Method
FETCH: method <anon> (Mu: *%_) { #`(Method|94229743999616) ... }
FETCH: Method
FETCH: method <anon> (Mu: *%_) { #`(Method|94229743999616) ... }
FETCH: Method
FETCH: method <anon> (Mu: *%_) { #`(Method|94229743999616) ... }
FETCH: Method
FETCH: method <anon> (Mu: *%_) { #`(Method|94229743999616) ... }
FETCH: Method
FETCH: method <anon> (Mu: *%_) { #`(Method|94229743999616) ... }
FETCH: Method
FETCH: method <anon> (Mu: *%_) { #`(Method|94229743999616) ... }
FETCH: Method
True
Run Code Online (Sandbox Code Playgroud)

谁能解释一下这里发生了什么?谢谢!

jjm*_*elo 5

问题是$!string在实际调用块时是一个空容器。即使它是在作用域中声明的,到实际使用时它$!str也确实指向了一个匿名方法。只需添加say $!string您的FETCHor STORE,您就会看到它包含一个匿名的Block、打印的<anon>。如果您想要处理属性,请检查此其他 SO 答案以了解如何完成。