what's the equivalent method of __init__ in Perl 6?

Answers by Christopher Bottoms and Brad Gilbert are right. However, I would like to point out a few things that might make it easier to understand equivalences between Python and Perl6. First, this page about going from Python to Perl6 is full with them, including this section on classes and objects.

Please note that the equivalent to __init__ in Perl6 is... nothing. Constructors are generated automatically from instance variables, including defaults. Calling the constructor, however, needs only the name of the class in Python, while it uses new in Perl 6.

On the other hand, there are many different ways of overriding that default behavior, from defining your own new to using BUILD, BUILDALL or, even better, TWEAK (which are commonly defined as submethods, so not inherited by subclasses).

Finally, you do have self to refer to the object itself within Perl 6 methods. However, we will usually see it this way (as in the examples above) self.instance-variable$!instance-variable (and please note that - can be validly part of an identifier in Perl 6).


In Perl 6, there is the default new constructor for every class that you can use to initialize the attributes of the object:

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;

Gives the following output:

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

I recommend checking out the Class and Object tutorial and the page on Object Orientation (the latter page includes the Object Construction section mentioned by Håkon Hægland in the comments to your question).


To be pedantic the closest syntactic equivalent would be to create a submethod BUILD (or TWEAK).

This is the closest translation:

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

This is a little more idiomatic

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

To be really idiomatic I would write what Christopher did.

Tags:

Python

Raku