Journal(2005) | Blog(2006) | RandomLink | WhoAmI | LiveBookmark | HomePage

<<Previous: class Examples11 is Perl6 { ... }  >>Next: role Example13 { # Perl6 }

$Perl6 = $class.bless(:Example<12>);

Category: Perl6   Keywords: class Perl6

Pause

I'm sorry. pugs 还有很多没有实现,所以我也不知道写下来的是否正确,所以就先等等了。
本章只是占个地方。可以略过不看。等 pugs 实现了 bless 等我会慢慢加进来。

构建和初始化

所有的类都从 Object 类继承了一个构建函数 new. 它能将传递进来的参数(只能是带名参数)分别初始化对应的属性。
Class Dog {
    has $.name;
    ...

my $pet = Dog.new(:name<Eric>); # 这里的 new 继承自 Object, 而传递进来的 :name<Eirc> 将初始化 $.name
你可以自己写 new 来覆盖 Object 的 new.
或者写你喜欢名字的构建器。与 Perl 5 中一样,一个构件器就是调用了 bless 的例程,不同的是类中调用的是方法。
因为 pugs 还没实现 bless, 所以我也试不出来。只能暂时缓缓。

submethod BUILD

class Dog {
    has $.name;
    has $.mum;
    has $:age;
    
    submethod BUILD ($.name) {
        $.name ~= ' Lam';
    }
}
my $pet = Dog.new( :name<Snoopy>, :mum<Kitty>, :age<2> );
say $pet.name; # Snoopy Lam
前面讲过 submethod 与 method 不同的是 submethod 是不会被继承的。
这里的 BUILD 方法覆盖了 Object 里的方法。函数 bless 会通过调用 BUILDALL 来自动调用合适的 BUILD

clone

class Dog {
    has $.name;
    has $.mum;
    has $:age;
    ...
}
my $pet = Dog.new( :name<Snoopy>, :mum<Kitty>, :age<2> );
...
my $pet2 = $pet.clone(:name<Lily>);
# 除了名字改为 Lily, 其 mum, age 都跟 $pet 一样,而且可以调用 $pet 能调用的东西

<<Previous: class Examples11 is Perl6 { ... }  >>Next: role Example13 { # Perl6 }

Options: +Del.icio.us

Related items Created on 2005-05-31 11:38:46, Last modified on 2005-05-31 13:07:22
Copyright 2004-2005 All Rights Reserved. Powered by Eplanet && Catalyst 5.62.