Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

raku

In Python, __init__ used to initialize a class:

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

what's the equivalent method of init in Perl 6? Is the method new?

like image 308
chenyf Avatar asked Mar 28 '18 15:03

chenyf


2 Answers

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

like image 126
Christopher Bottoms Avatar answered Oct 08 '22 20:10

Christopher Bottoms


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

like image 40
jjmerelo Avatar answered Oct 08 '22 20:10

jjmerelo