在 Raku class 定义中 "method" 之前的 "has" 关键字是什么意思?
What does the "has" keyword mean before "method" in a Raku class definition?
最近我意识到我完全错误地写了一个我的 Raku 类 这样的:
class Foo {
has method bar {
return 'some string';
}
}
我惊讶地发现 has method
不是错误,并且按预期工作。
在这种情况下 has
在做什么?这是故意的行为吗?
has
是范围声明符,与 my
、our
、state
和 anon
属于同一类别。 has
-scoped 的东西安装在当前包的 meta-class 中。
Variable-like 事物总是以明确的范围声明,例如:
my $lexical-var;
my $.lexical-var-with-accessor;
has $!attribute;
has $.attribute-with-accessor;
许多其他构造可以可选地指定它们的范围,但带有合理的默认值。例如:
my sub marine() { }
- 与没有 my
相同
our class Struggle { }
- 与没有 our
相同
has method in-the-madness() { }
- 与没有 has
相同
最常见的方法替代范围可能是 anon
,这在 meta-programming 时很有用。例如,如果我们正在编写一个 class 将要使用 MOP 构造另一个 class,我们可以这样写:
$the-class.^add_method('name', anon method name() { $name });
这意味着我们最终不会在当前 class 上安装方法 name
。但是,大多数时候,我们希望 has
范围。明确指定它没有坏处,就像在 sub
之前写 my
没有坏处一样;它只是重申一个默认值。
最近我意识到我完全错误地写了一个我的 Raku 类 这样的:
class Foo {
has method bar {
return 'some string';
}
}
我惊讶地发现 has method
不是错误,并且按预期工作。
在这种情况下 has
在做什么?这是故意的行为吗?
has
是范围声明符,与 my
、our
、state
和 anon
属于同一类别。 has
-scoped 的东西安装在当前包的 meta-class 中。
Variable-like 事物总是以明确的范围声明,例如:
my $lexical-var;
my $.lexical-var-with-accessor;
has $!attribute;
has $.attribute-with-accessor;
许多其他构造可以可选地指定它们的范围,但带有合理的默认值。例如:
my sub marine() { }
- 与没有my
相同
our class Struggle { }
- 与没有our
相同
has method in-the-madness() { }
- 与没有has
相同
最常见的方法替代范围可能是 anon
,这在 meta-programming 时很有用。例如,如果我们正在编写一个 class 将要使用 MOP 构造另一个 class,我们可以这样写:
$the-class.^add_method('name', anon method name() { $name });
这意味着我们最终不会在当前 class 上安装方法 name
。但是,大多数时候,我们希望 has
范围。明确指定它没有坏处,就像在 sub
之前写 my
没有坏处一样;它只是重申一个默认值。