在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中标识符的一部分).
在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)
给出以下输出:
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")
我建议查看Class和Object教程以及Object Orientation页面(后一页包含HåkonHægland在您的问题的评论中提到的Object Construction部分).
要迂腐,最接近的句法等价物就是创造一个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)
为了真正惯用,我会写出克里斯托弗所做的.
| 归档时间: |
|
| 查看次数: |
368 次 |
| 最近记录: |