是否可以在 Raku 中访问 class 之外的静态方法和属性?
Is it possible to access static methods and attributes outside the class in Raku?
在 raku 中,似乎可以定义静态方法(通过 sub
关键字)和静态属性(通过 my
),它们可以在同一个 class.[=14 中引用=]
但是,是否可以在 class 之外访问这些方法和属性?
与此类似的内容:
class MyClass {
my $attribute = 123;
sub my-method {
say 'Hello';
}
}
MyClass.$attribute;
MyClass.my-method;
it seems possible to define static methods (via sub
keyword) and static attributes (via my
) Those can be referenced inside the same class.
我明白你为什么称它们为静态方法和属性,但 Raku 有一个更简单的解决方案:
class MyClass {
method my-method {
say 'Hello';
}
method attribute is rw {
state $attribute = 123
}
}
say MyClass.attribute; # 123
MyClass.attribute = 99;
say MyClass.attribute; # 99
MyClass.my-method; # Hello
您可以使用our sub
和our
变量。 our
是用于定义词法的声明符,该词法是 也 用于在其声明的包之外使用。 (my
是 从未 共享的;没有 our
的 sub
声明符与 my sub
相同。)
所以:
class MyClass {
our sub my-sub {
say 'Hello';
}
our $attribute = 123
}
import MyClass;
say $MyClass::attribute; # 123
$MyClass::attribute = 99;
say $MyClass::attribute; # 99
MyClass::my-sub; # Hello
如您所见,这些不是方法;这种方法在先前的解决方案没有的意义上忽略了 OOP。
在 raku 中,似乎可以定义静态方法(通过 sub
关键字)和静态属性(通过 my
),它们可以在同一个 class.[=14 中引用=]
但是,是否可以在 class 之外访问这些方法和属性?
与此类似的内容:
class MyClass {
my $attribute = 123;
sub my-method {
say 'Hello';
}
}
MyClass.$attribute;
MyClass.my-method;
it seems possible to define static methods (via
sub
keyword) and static attributes (viamy
) Those can be referenced inside the same class.
我明白你为什么称它们为静态方法和属性,但 Raku 有一个更简单的解决方案:
class MyClass {
method my-method {
say 'Hello';
}
method attribute is rw {
state $attribute = 123
}
}
say MyClass.attribute; # 123
MyClass.attribute = 99;
say MyClass.attribute; # 99
MyClass.my-method; # Hello
您可以使用our sub
和our
变量。 our
是用于定义词法的声明符,该词法是 也 用于在其声明的包之外使用。 (my
是 从未 共享的;没有 our
的 sub
声明符与 my sub
相同。)
所以:
class MyClass {
our sub my-sub {
say 'Hello';
}
our $attribute = 123
}
import MyClass;
say $MyClass::attribute; # 123
$MyClass::attribute = 99;
say $MyClass::attribute; # 99
MyClass::my-sub; # Hello
如您所见,这些不是方法;这种方法在先前的解决方案没有的意义上忽略了 OOP。