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
?
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).
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With