Perl 6中__init__的等效方法是什么?

che*_*nyf 9 python raku

在Python中,__init__用于初始化类:

class Auth(object):
    def __init__(self, oauth_consumer, oauth_token=None, callback=None):
        self.oauth_consumer = oauth_consumer
        self.oauth_token = oauth_token or {}
        self.callback = callback or 'http://localhost:8080/callback'

    def HMAC_SHA1():
        pass
Run Code Online (Sandbox Code Playgroud)

Perl 6 中init的等效方法是什么?是方法new吗?

jjm*_*elo 10

Christopher Bottoms和Brad Gilbert的回答是正确的.但是,我想指出一些可能更容易理解Python和Perl6之间等价的事情.首先,关于从Python到Perl6的这个页面已经完整,包括关于类和对象的这一部分.

请注意,__init__在Perl6中相当于...... 没有.构造函数是从实例变量自动生成的,包括默认值.但是,调用构造函数只需要Python中类的名称,而它new在Perl 6中使用.

另一方面,有许多不同的方法可以覆盖默认行为,从定义自己new到使用BUILD,BUILDALL或者甚至更好TWEAK(通常被定义为submethods,因此不会被子类继承).

最后,您必须self在Perl 6方法中引用对象本身.但是,我们通常会以这种方式看到它(如上例所示)self.instance-variable$!instance-variable(请注意,-它可以有效地成为Perl 6中标识符的一部分).

  • "它通常缩写为"不确定"它的"在这里指的是什么.我假设它是实例变量,但从文本的上下文来看,这可以解释为应用于`self`,这是错误的. (2认同)
  • 说"BUILD,BUILDALL [...]或TWEAK这些被称为子方法"可能有点误导.如果将它们定义为`submethod`,它们只是子方法.它们通常被定义为这样,这就是它们不可继承的原因.但是,如果将它们定义为`method`,它们将是可继承的. (2认同)

Chr*_*oms 9

在Perl 6中,new每个类都有一个默认构造函数,可用于初始化对象的属性:

class Auth {
    has $.oauth_consumer is required;
    has $.oauth_token = {} ;
    has $.callback = 'http://localhost:8080/callback';

    method HMAC_SHA1() { say 'pass' }
}

my $auth = Auth.new( oauth_consumer => 'foo');

say "Calling method HMAC_SHA1:";

$auth.HMAC_SHA1;

say "Data dump of object $auth:";

dd $auth;
Run Code Online (Sandbox Code Playgroud)

给出以下输出:

Calling method HMAC_SHA1:
pass
Data dump of object Auth<53461832>:
Auth $auth = Auth.new(oauth_consumer => "foo", oauth_token => ${}, callback => "http://localhost:8080/callback")
Run Code Online (Sandbox Code Playgroud)

我建议查看Class和Object教程以及Object Orientation页面(后一页包含HåkonHægland在您的问题的评论中提到的Object Construction部分).

  • 请注意,如果属性没有默认值但必须*指定,则也可以将属性标记为"必需".您还可以争辩说Rakudo Perl 6会自动为您生成`init`方法. (2认同)
  • @ElizabethMattijsen 谢谢!根据您的建议进行编辑。我认为 Python 语法会使“oauth_consumer”成为必需的。在 Perl 6 中,不必将所有公共属性列出两次,这真是太好了。 (2认同)

Bra*_*ert 9

要迂腐,最接近的句法等价物就是创造一个submethod BUILD(或TWEAK).

这是最接近的翻译:

class Auth {
    has $.oauth_consumer;
    has $.oauth_token;
    has $.callback;

    submethod BUILD ( \oauth_consumer, \oauth_token=Nil, \callback=Nil ) {
        $!oauth_consumer = oauth_consumer;
        $!oauth_token = oauth_token // {};
        $!callback = callback // 'http://localhost:8080/callback';
    }

    method HMAC_SHA1 ( --> 'pass' ) {}
}
Run Code Online (Sandbox Code Playgroud)

这有点像惯用语

class Auth {
    has $.oauth_consumer;
    has $.oauth_token;
    has $.callback;

    submethod BUILD (
        $!oauth_consumer,
        $!oauth_token = {},
        $!callback = 'http://localhost:8080/callback',
    ) {
        # empty submethod
    }

    method HMAC_SHA1 ( --> 'pass' ) {}
}
Run Code Online (Sandbox Code Playgroud)

为了真正惯用,我会写出克里斯托弗所做的.