代码之家  ›  专栏  ›  技术社区  ›  chenyf

Perl 6中的\uu init\uuuu等效方法是什么?

  •  10
  • chenyf  · 技术社区  · 7 年前

    在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
    

    等效的方法是什么 初始化 在Perl 6中?是方法 new ?

    3 回复  |  直到 5 年前
        1
  •  11
  •   raiph    7 年前

    克里斯托弗·巴茨和布拉德·吉尔伯特的答案是正确的。然而,我想指出一些事情,这些事情可能会使我们更容易理解Python和Perl6之间的等效性。 第一 this page about going from Python to Perl6 到处都是,包括 this section on classes and objects

    请注意,等效于 __init__ 在Perl6中是。。。 没有什么 。构造函数是从实例变量(包括默认值)自动生成的。然而,调用构造函数只需要Python中类的名称,而它使用 new 在Perl 6中。

    另一方面 there are many different ways of overriding that default behavior ,定义自己的 到使用 BUILD , BUILDALL or, even better, TWEAK (通常定义为 submethods ,因此不会被子类继承)。

    最后,你有 self 在Perl 6方法中引用对象本身。然而,我们通常会这样看(如上面的示例所示) self.instance-variable ††† $!instance-variable (请注意 - 可以是Perl 6中标识符的有效部分)。

        2
  •  10
  •   Christopher Bottoms zerkms    7 年前

    在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;
    

    提供以下输出:

    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")
    

    我建议您查看 Class and Object tutorial 和上的页面 Object Orientation (后一页包括 Object Construction section HÃ¥kon HÃalgland在对您的问题的评论中提到)。

        3
  •  9
  •   Brad Gilbert    7 年前

    要学究式,最接近的语法等价物是创建 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' ) {}
    }
    

    这有点惯用

    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' ) {}
    }
    

    为了真正地道,我会写克里斯托弗所做的。