=encoding euc-jp =head1 NAME =begin original perlboot - Beginner's Object-Oriented Tutorial =end original perlboot - Perl オブジェクト指向導入編 =head1 DESCRIPTION =begin original If you're not familiar with objects from other languages, some of the other Perl object documentation may be a little daunting, such as L, a basic reference in using objects, and L, which introduces readers to the peculiarities of Perl's object system in a tutorial way. =end original 他の言語でオブジェクトに親しんでいたのでなければ、他の Perl オブジェクトの ドキュメントのいくつかは気力をくじかせるでしょう; オブジェクトを使うための基本的なリファレンス L、Perl の オブジェクトシステムの特性のチュートリアル的な紹介 L 等のように。 =begin original So, let's take a different approach, presuming no prior object experience. It helps if you know about subroutines (L), references (L et. seq.), and packages (L), so become familiar with those first if you haven't already. =end original そこで、別のアプローチをとって、オブジェクトの経験がないことを 前提にしましょう。 もし、サブルーチン(L)や、リファレンス(L等)、 パッケージ(L) を知っているのならそれが役に立ちますので、 もしまだわからなければまずそちらを先に知っておくべきでしょう。 =head2 If we could talk to the animals... (もし動物と会話できたら…) =begin original Let's let the animals talk for a moment: =end original 動物さんたちにちょっとしゃべってもらいましょう。 sub Cow::speak { print "a Cow goes moooo!\n"; } sub Horse::speak { print "a Horse goes neigh!\n"; } sub Sheep::speak { print "a Sheep goes baaaah!\n"; } Cow::speak; Horse::speak; Sheep::speak; =begin original This results in: =end original これは次の結果を得ます: a Cow goes moooo! a Horse goes neigh! a Sheep goes baaaah! =begin original Nothing spectacular here. Simple subroutines, albeit from separate packages, and called using the full package name. So let's create an entire pasture: =end original 目新しいことはありません。 別々のパッケージに分かれていて完全なパッケージ名を使って呼び出していますが、 単なるサブルーチンです。 では、牧場を作ってみましょう。 # Cow::speak, Horse::speak, Sheep::speak as before @pasture = qw(Cow Cow Horse Sheep Sheep); foreach $animal (@pasture) { &{$animal."::speak"}; } =begin original This results in: =end original これは次の結果を得ます: a Cow goes moooo! a Cow goes moooo! a Horse goes neigh! a Sheep goes baaaah! a Sheep goes baaaah! =begin original Wow. That symbolic coderef de-referencing there is pretty nasty. We're counting on C mode, certainly not recommended for larger programs. And why was that necessary? Because the name of the package seems to be inseparable from the name of the subroutine we want to invoke within that package. =end original うわ。 ここにあるシンボリック coderef のデリファレンスはかなり粗雑です。 C モードも考えてみると、大きなプログラムには全然向きません。 なぜその様なものが必要とされるのでしょう? それはパッケージ名を、そのパッケージの呼び出そうとしているサブルーチンの 名前から分離できないからです。 =begin original Or is it? =end original ではどうしましょう? =head2 Introducing the method invocation arrow (メソッド呼び出しの矢印) =begin original For now, let's say that C<< Class->method >> invokes subroutine C in package C. (Here, "Class" is used in its "category" meaning, not its "scholastic" meaning.) That's not completely accurate, but we'll do this one step at a time. Now let's use it like so: =end original いまのところ、C<< Class->method >> は C パッケージの C サブルーチンを呼び出すとだけ言っておきましょう。 (ここで "Class" は "カテゴリ" の意味です; "学級" ではありません。) 完全に厳密ではありませんが、少しずつ進めていきましょう。 これは次のように使います: # Cow::speak, Horse::speak, Sheep::speak as before Cow->speak; Horse->speak; Sheep->speak; =begin original And once again, this results in: =end original そしてこれは次の結果を得ます: a Cow goes moooo! a Horse goes neigh! a Sheep goes baaaah! =begin original That's not fun yet. Same number of characters, all constant, no variables. But yet, the parts are separable now. Watch: =end original 別におもしろくもありませんね。 同じ文字数ですし全て定数で変数もありません。 でも、今度はパッケージ名を分離できるのです。 次を見てください: $a = "Cow"; $a->speak; # invokes Cow->speak =begin original Ahh! Now that the package name has been parted from the subroutine name, we can use a variable package name. And this time, we've got something that works even when C is enabled. =end original ああ! 関数名からパッケージ名を分けれるので、パッケージ名に変数を 使うことができるのです。 そして今度は C が有効であってもちゃんと機能するのです。 =head2 Invoking a barnyard (裏庭の呼び出し) =begin original Let's take that new arrow invocation and put it back in the barnyard example: =end original 新しい矢印呼び出しを使って、裏庭の例に戻ってみましょう: sub Cow::speak { print "a Cow goes moooo!\n"; } sub Horse::speak { print "a Horse goes neigh!\n"; } sub Sheep::speak { print "a Sheep goes baaaah!\n"; } @pasture = qw(Cow Cow Horse Sheep Sheep); foreach $animal (@pasture) { $animal->speak; } =begin original There! Now we have the animals all talking, and safely at that, without the use of symbolic coderefs. =end original みんなちゃんとしゃべってくれます! また今度はシンボリック coderef を使っていなくて安全です。 =begin original But look at all that common code. Each of the C routines has a similar structure: a C operator and a string that contains common text, except for two of the words. It'd be nice if we could factor out the commonality, in case we decide later to change it all to C instead of C. =end original でも、コードをよく見てみると、各 C 関数はよく似た構造を持っています。 C 演算子と、2 語を除くと同一のテキストを含んでいるだけです。 共通箇所を分解するのはよいことです; 例えば、後で全ての C を C に 変えることもできるようになります。 =begin original And we actually have a way of doing that without much fuss, but we have to hear a bit more about what the method invocation arrow is actually doing for us. =end original また、大騒ぎすることなくそれを行う方法も実際ありますが、メソッド呼び出しの 矢印が何を行ってくれているのかについてここで少し 知っておかなければなりません。 =head2 The extra parameter of method invocation (メソッド呼び出しの追加パラメータ) =begin original The invocation of: =end original メソッド呼び出し: Class->method(@args) =begin original attempts to invoke subroutine C as: =end original は、C 関数を次のように呼び出そうとします: Class::method("Class", @args); =begin original (If the subroutine can't be found, "inheritance" kicks in, but we'll get to that later.) This means that we get the class name as the first parameter (the only parameter, if no arguments are given). So we can rewrite the C speaking subroutine as: =end original (もし関数を見つけることができなかったときには、「継承」が走査されます。 これに関してはあとで説明します。) これは最初のパラメータとしてクラス名を得ることを意味します (もし引数がなければそれがただ一つのパラメータになります)。 このことから C のおしゃべり関数を次のように書き改めることができます: sub Sheep::speak { my $class = shift; print "a $class goes baaaah!\n"; } =begin original And the other two animals come out similarly: =end original また他の動物たちも同様になります: sub Cow::speak { my $class = shift; print "a $class goes moooo!\n"; } sub Horse::speak { my $class = shift; print "a $class goes neigh!\n"; } =begin original In each case, C<$class> will get the value appropriate for that subroutine. But once again, we have a lot of similar structure. Can we factor that out even further? Yes, by calling another method in the same class. =end original それぞれにおいて C<$class> にはその関数の特定の値を得ます。 しかしもう一度考え直してみると、かなりよく似た構造になっています。 さらに分離することはできないでしょうか? それは同じクラスの別のメソッドを呼ぶことで可能です。 =head2 Calling a second method to simplify things (簡単に 2 つ目のメソッドを呼び出す) =begin original Let's call out from C to a helper method called C. This method provides the constant text for the sound itself. =end original C から補助メソッド C を呼び出してみましょう。 このメソッドはその鳴き声として固定文字列を提供します。 { package Cow; sub sound { "moooo" } sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n"; } } =begin original Now, when we call C<< Cow->speak >>, we get a C<$class> of C in C. This in turn selects the C<< Cow->sound >> method, which returns C. But how different would this be for the C? =end original さて、C<< Cow->speak >> を呼び出すと C では C<$class> として C を得ました。 これを使って C を返す C<< Cow->sound >> メソッドを選択します。 では C の時はどこが変わるでしょう。 { package Horse; sub sound { "neigh" } sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n"; } } =begin original Only the name of the package and the specific sound change. So can we somehow share the definition for C between the Cow and the Horse? Yes, with inheritance! =end original パッケージ名と鳴き声の指定だけが変わりました。 ところで Cow と Horse で C の定義を共有する方法はないでしょうか? それが継承です! =head2 Inheriting the windpipes (気管を継承する) =begin original We'll define a common subroutine package called C, with the definition for C: =end original 共通の関数のパッケージとして C を作ります; ここで C を定義します { package Animal; sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n"; } } =begin original Then, for each animal, we say it "inherits" from C, along with the animal-specific sound: =end original 次に各動物たちに対して、それぞれの鳴き声の定義と一緒に、 C から「継承」します: { package Cow; @ISA = qw(Animal); sub sound { "moooo" } } =begin original Note the added C<@ISA> array (pronounced "is a"). We'll get to that in a minute. =end original ここで、C<@ISA> (「イズア」と発音します))配列が加えられていることに 注意してください。 少々これについて説明します。 =begin original But what happens when we invoke C<< Cow->speak >> now? =end original ところで、ここで C<< Cow->speak >> を呼び出すとなにが起こるのでしょう? =begin original First, Perl constructs the argument list. In this case, it's just C. Then Perl looks for C. But that's not there, so Perl checks for the inheritance array C<@Cow::ISA>. It's there, and contains the single name C. =end original まず、Perl が引数リストを構築します。 今回は単純に C だけです。 それから Perl は C を探します。 しかしそれはありません; そのため Perl は継承配列 C<@Cow::ISA> を調べます。 それは存在し、名前を一つ C を格納しています。 =begin original Perl next checks for C inside C instead, as in C. And that's found, so Perl invokes that subroutine with the already frozen argument list. =end original Perl は次に C の C を C の様に調べます。 今度は見つかりました; そこで Perl はこの関数をさっき作っておいた引数リストで 呼び出します。 =begin original Inside the C subroutine, C<$class> becomes C (the first argument). So when we get to the step of invoking C<< $class->sound >>, it'll be looking for C<< Cow->sound >>, which gets it on the first try without looking at C<@ISA>. Success! =end original C 関数においては、C<$class> は C になります (これが一つめの引数です)。 そのため C<< $class->sound >> の呼び出しにおいて C<< Cow->sound >> を 得ます; 最初は C<@ISA> を探すことなく調べます。 そしてこれは成功します。 =head2 A few notes about @ISA (@ISA に関して追記) =begin original This magical C<@ISA> variable has declared that C "is a" C. Note that it's an array, not a simple single value, because on rare occasions, it makes sense to have more than one parent class searched for the missing methods. =end original この魔法の C<@ISA> 変数は、C が C の「一種である(is-a)」と 宣言しています。 これが単なる一つの値ではなく配列であることに注意してください; 稀ではありますが、メソッドが見つからなかったときに探す親クラスを 一つ以上もつこともあるためです。 =begin original If C also had an C<@ISA>, then we'd check there too. The search is recursive, depth-first, left-to-right in each C<@ISA> by default (see L for alternatives). Typically, each C<@ISA> has only one element (multiple elements means multiple inheritance and multiple headaches), so we get a nice tree of inheritance. =end original もし C も C<@ISA> をもっていたらそれも同様に調べられます。 デフォルトでは、検索は C<@ISA> の中を再帰的に、深さ優先、左から右に 行われます(代替案については L を参照してください)。 典型的に、各 C<@ISA> がただ1つのみ要素を持っています (複数の要素を持っていれば複数の継承、複数の難問を持っています); そのため良好な継承ツリーを得ます。 =begin original When we turn on C, we'll get complaints on C<@ISA>, since it's not a variable containing an explicit package name, nor is it a lexical ("my") variable. We can't make it a lexical variable though (it has to belong to the package to be found by the inheritance mechanism), so there's a couple of straightforward ways to handle that. =end original C を有効にしたとき、C<@ISA> は明示的なパッケージ名を 持っていないため、そしてレキシカル変数 ("my") でもないため警告を受けます。 この変数はレキシカル変数にはできません; (継承メカニズムが探索できるように、パッケージに属していなければなりません) これに対処する方法は 2 つあります。 =begin original The easiest is to just spell the package name out: =end original 一番簡単な方法はパッケージ名をつけて使うことです: @Cow::ISA = qw(Animal); =begin original Or declare it as package global variable: =end original またはこれをパッケージグローバル変数として宣言します: package Cow; our @ISA = qw(Animal); =begin original Or allow it as an implicitly named package variable: =end original もしくは暗黙に名付けられたパッケージ変数を許可することです: package Cow; use vars qw(@ISA); @ISA = qw(Animal); =begin original If the C class comes from another (object-oriented) module, then just employ C to specify that C should serve as the basis for the C class: =end original C クラスが他の (オブジェクト指向) モジュールから来ている場合、 C が C クラスの規定となることを指定するために、単に C を使います: package Cow; use base qw(Animal); =begin original Now that's pretty darn simple! =end original これでかなり単純になりました! =head2 Overriding the methods (メソッドのオーバーライド) =begin original Let's add a mouse, which can barely be heard: =end original ねずみを追加してみましょう; その声は微かでしょう。 # Animal package from before { package Mouse; @ISA = qw(Animal); sub sound { "squeak" } sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n"; print "[but you can barely hear it!]\n"; } } Mouse->speak; =begin original which results in: =end original これは次の結果になります: a Mouse goes squeak! [but you can barely hear it!] =begin original Here, C has its own speaking routine, so C<< Mouse->speak >> doesn't immediately invoke C<< Animal->speak >>. This is known as "overriding". In fact, we don't even need to say that a C is an C at all, because all of the methods needed for C are completely defined for C; this is known as "duck typing": "If it walks like a duck and quacks like a duck, I would call it a duck" (James Whitcomb). However, it would probably be beneficial to allow a closer examination to conclude that a C is indeed an C, so it is actually better to define C with C as its base (that is, it is better to "derive C from C"). =end original ここでは C は C<< Animal->speak >> を呼ぶのではなく 自分用のおしゃべりルーティン C<< Mouse->speak >> を持っています。 これは、「オーバーライド」と呼ばれています。 事実、C が C の一種であるという必要はまったくありません。 おしゃべり(C)に必要なメソッドは全て C に定義されています; これは「ダックタイピング」(duck typing) として知られています": 「あひるのように歩いてあひるのように鳴くなら、あひると呼ぼう」 (James Whitcomb)。 しかし、C が確かに C であると結論づけるためのより詳細な検査を 出来ることはおそらく有益なので、実際には C を基底として C を 定義する方が良い(つまり、「C から C を派生させる方が 良い」)です。 =begin original Moreover, this duplication of code could become a maintenance headache (though code-reuse is not actually a good reason for inheritance; good design practices dictate that a derived class should be usable wherever its base class is usable, which might not be the outcome if code-reuse is the sole criterion for inheritance. Just remember that a C should always act like an C). =end original さらに、このような重複は頭痛の種となります (しかしコードの再利用は 実際には継承の良い理由ではありません; よい設計プラクティスは基底クラスが 使えるところではどこでも派生クラスが使えるべきと指示していて、 コードの再利用が継承の唯一の基準だと効果がないかもしれません。 単に C は常に C のように動作するべきと言うことを 覚えておいてください)。 =begin original So, let's make C an C! =end original それで、C を C にしましょう! =begin original The obvious solution is to invoke C directly: =end original 明らかな解決方法は C を直接起動することです: # Animal package from before { package Mouse; @ISA = qw(Animal); sub sound { "squeak" } sub speak { my $class = shift; Animal::speak($class); print "[but you can barely hear it!]\n"; } } =begin original Note that we're using C. If we were to invoke C<< Animal->speak >> instead, the first parameter to C would automatically be C<"Animal"> rather than C<"Mouse">, so that the call to C<< $class->sound >> in C would become C<< Animal->sound >> rather than C<< Mouse->sound >>. =end original C を使っていることに注意してください。 代わりに C<< Animal->speak >> を起動すると、C への最初の引数は C<"Mouse"> ではなく自動的に C<"Animal"> になるので、C での C<< $class->sound >> の呼び出しは C<< Mouse->sound >> ではなく C<< Animal->sound >> になります。 =begin original Also, without the method arrow C<< -> >>, it becomes necessary to specify the first parameter to C ourselves, which is why C<$class> is explicitly passed: C. =end original また、メソッド矢印 C<< -> >> なしだと、C への最初の引数を 自分自身で指定する必要があるようになります; これが C<$class> が明示的に 渡されている理由です: C。 =begin original However, invoking C directly is a mess: Firstly, it assumes that the C method is a member of the C class; what if C actually inherits C from its own base? Because we are no longer using C<< -> >> to access C, the special method look up mechanism wouldn't be used, so C wouldn't even be found! =end original しかし、直接 C を起動するのは大変です: 最初に、C メソッドは C クラスのメンバであることを仮定しています; C が実際には独自の基底クラスから C を継承していたら? もはや C にアクセスするのに C<< -> >> を使わないので、特別なメソッド 検索機構が使われておらず、C は発見すらされていません! =begin original The second problem is more subtle: C is now hardwired into the subroutine selection. Let's assume that C does exist. What happens when, at a later time, someone expands the class hierarchy by having C inherit from C instead of C. Unless the invocation of C is also changed to an invocation of C, centuries worth of taxonomical classification could be obliterated! =end original 二つ目の問題はより微妙です: C はサブルーチン選択に ハードコーディングされています。 C が存在すると仮定してみましょう。 後で起こることは、誰かが C を C ではなく C から 継承することでクラス階層を拡張します。 C の起動が C の起動も変更されない限り、 分類学の世紀的な価値が破壊されます! =begin original What we have here is a fragile or leaky abstraction; it is the beginning of a maintenance nightmare. What we need is the ability to search for the right method wih as few assumptions as possible. =end original ここにあるものは脆弱で漏れやすい抽象化です; これは保守の悪夢の始まりです。 必要としているものは出来るだけ仮定を少なくして正しいメソッドを探す能力です。 =head2 Starting the search from a different place (異なる場所から探索を始める) =begin original A I solution is to tell Perl where in the inheritance chain to begin searching for C. This can be achieved with a modified version of the method arrow C<< -> >>: =end original I<よりよい> 解決法は、継承チェーンのどこから C の検索を始めるのかを Perl に伝えることです。 これはメソッド矢印 C<< -> >> の修正版で達成できます: ClassName->FirstPlaceToLook::method =begin original So, the improved C class is: =end original それで、改良された C クラスは: # same Animal as before { package Mouse; # same @ISA, &sound as before sub speak { my $class = shift; $class->Animal::speak; print "[but you can barely hear it!]\n"; } } =begin original Using this syntax, we start with C to find C, and then use all of C's inheritance chain if it is not found immediately. As usual, the first parameter to C would be C<$class>, so we no longer need to pass C<$class> explicitly to C. =end original この構文を使うことで、C の探索を C から開始することができ、 それから直接見つからなくても C の全ての継承連鎖を使う ことができます。 いつも通り、C への一つめのパラメータは C<$class> になるため、 もはや C<$class> を明示的に C に渡す必要はありません。 =begin original But what about the second problem? We're still hardwiring C into the method lookup. =end original しかし、二つ目の問題はどうでしょう? まだメソッド検索に C をハードコーディングしています。 =head2 The SUPER way of doing things (SUPER 解答) =begin original If C is replaced with the special placeholder C in that invocation, then the contents of C's C<@ISA> are used for the search, beginning with C<$ISA[0]>. So, all of the problems can be fixed as follows: =end original この起動で C が特別なプレースホルダ C で置き換えられると、 C の C<@ISA> の内容が使われ、C<$ISA[0]> から始められます。 それで、以下のようにして全ての問題が修正できます: # same Animal as before { package Mouse; # same @ISA, &sound as before sub speak { my $class = shift; $class->SUPER::speak; print "[but you can barely hear it!]\n"; } } =begin original In general, C means look in the current package's C<@ISA> for a class that implements C, and invoke the first one found. The placeholder is called C, because many other languages refer to base classes as "Iclasses", and Perl likes to be eclectic. =end original 一般的に、C は現在のパッケージの C<@ISA> から C を 実装するクラスを探し、最初に見つかったものを呼び出します。 プレースホルダは C と呼ばれます; その他の言語では基底クラスを "Iclasses"(スーパークラス)として参照し、Perl は折衷主義だからです。 =begin original Note that a call such as =end original 以下のように呼び出すと $class->SUPER::method; =begin original does I look in the C<@ISA> of C<$class> unless C<$class> happens to be the current package. =end original C<$class> がたまたま現在のパッケージでない限り、C<$class> の C<@ISA> を I<見ない> ことに注意してください。 =head2 Let's review... =begin original So far, we've seen the method arrow syntax: =end original これまでに見てきたものは、メソッド矢印構文: Class->method(@args); =begin original or the equivalent: =end original その等価な文: $a = "Class"; $a->method(@args); =begin original which constructs an argument list of: =end original 構築される引数リスト: ("Class", @args) =begin original and attempts to invoke: =end original 呼び出され方: Class::method("Class", @args); =begin original However, if C is not found, then C<@Class::ISA> is examined (recursively) to locate a class (a package) that does indeed contain C, and that subroutine is invoked instead. =end original しかし、C が見つからなければ C<@Class::ISA> が(再帰的に) 実際 C を含んでいるクラス(パッケージ)を探すために使われます。 =begin original Using this simple syntax, we have class methods, (multiple) inheritance, overriding, and extending. Using just what we've seen so far, we've been able to factor out common code (though that's never a good reason for inheritance!), and provide a nice way to reuse implementations with variations. =end original この簡単な構文を使うことでクラスメソッド、(複数の)継承、オーバーライド、 そして拡張を行えるようになりました。 これまでに見てきたもので共通処理を抽出し、(しかし、これは決して継承のよい 理由ではありません!)、様々な実装に再利用する良好な方法を提供できます。 =begin original Now, what about data? =end original それで、データについては? =head2 A horse is a horse, of course of course -- or is it? (馬は馬、もちろん -- ですか?) =begin original Let's start with the code for the C class and the C class: =end original C クラスと C クラスを書いてみましょう。 { package Animal; sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n"; } } { package Horse; @ISA = qw(Animal); sub sound { "neigh" } } =begin original This lets us invoke C<< Horse->speak >> to ripple upward to C, calling back to C to get the specific sound, and the output of: =end original C<< Horse->speak >> を呼び出すことで C に渡り、そこから C に鳴き声を作りに戻ります; 結果は次のようになります: a Horse goes neigh! =begin original But all of our Horse objects would have to be absolutely identical. If we add a subroutine, all horses automatically share it. That's great for making horses the same, but how do we capture the distinctions of an individual horse? For example, suppose we want to give our first horse a name. There's got to be a way to keep its name separate from the other horses. =end original しかしこのすべての Horse オブジェクトは完全に同一です。 サブルーチンを追加しても、全ての馬が自動的にそれを共有します。 同じ馬を作るが目的ならすばらしいことですが、 個々の馬を識別したい時にはどうすれば良いのでしょうか? 例えば最初の馬に名前を付けたい時にはどうすれば良いのでしょう。 もちろん、それぞれの馬の名前を分離して維持する方法があります。 =begin original That is to say, we want particular instances of C to have different names. =end original これは言わば、特定の C のインスタンスに別の名前を付けたいです。 =begin original In Perl, any reference can be an "instance", so let's start with the simplest reference that can hold a horse's name: a scalar reference. =end original Perl では任意のリファレンスなら「インスタンス」になることができます; そこでまず単純なリファレンスとして、馬の名前を保持するスカラリファレンス を使ってみましょう。 my $name = "Mr. Ed"; my $horse = \$name; =begin original So, now C<$horse> is a reference to what will be the instance-specific data (the name). The final step is to turn this reference into a real instance of a C by using the special operator C: =end original これで C<$talking> はインスタンス指向のデータ(名前)のリファレンスに なりました。 最後のステップは特別な演算子 C を使ってこのリファレンスを実際の C のインスタンスにすることです。 bless $horse, Horse; =begin original This operator stores information about the package named C into the thing pointed at by the reference. At this point, we say C<$horse> is an instance of C. That is, it's a specific horse. The reference is otherwise unchanged, and can still be used with traditional dereferencing operators. =end original これはパッケージ名 C に関する情報をリファレンスに指されているものに 格納する操作を行います。 これにより、C<$horse> が C のインスタンスになったといいます。 これで、個々の馬を識別できます。 リファレンスはそれ以外に変化はありませんし、伝統的なデリファレンス操作を 使うこともできます。 =head2 Invoking an instance method (インスタンスメソッドの呼び出し) =begin original The method arrow can be used on instances, as well as classes (the names of packages). So, let's get the sound that C<$horse> makes: =end original メソッド矢印はクラス(パッケージ名)の時と同じように、インスタンスに対しても 使うことができます。 では、C<$horse> の作り出す音を取り出してみましょう: my $noise = $horse->sound("some", "unnecessary", "args"); =begin original To invoke C, Perl first notes that C<$horse> is a blessed reference (and thus an instance). It then constructs an argument list, as per usual. =end original C を呼び出すために、Perl は始めに C<$horse> が bless された リファレンス(つまりインスタンス)であることを確認します。 それからいつも通り引数リストを構成します。 =begin original Now for the fun part: Perl takes the class in which the instance was blessed, in this case C, and uses that class to locate the subroutine. In this case, C is found directly (without using inheritance). In the end, it is as though our initial line were written as follows: =end original さて、ここがおもしろいところです: Perl はインスタンスが bless されている クラス、今回は C を取り出し、サブルーチンの場所を特定するためにその クラスを使います。 今回は、C が直接に (継承を使うことなしに) 見つかります。 結局、最初の行は以下のように書いたかのようになります: my $noise = Horse::sound($horse, "some", "unnecessary", "args"); =begin original Note that the first parameter here is still the instance, not the name of the class as before. We'll get C as the return value, and that'll end up as the C<$noise> variable above. =end original この最初のパラメータは、先ほどのようなクラス名ではなく、インスタンスの ままである点に注意してください。 この結果 C を復帰値として受け取り、これが C<$noise> 変数に 代入されます。 =begin original If Horse::sound had not been found, we'd be wandering up the C<@Horse::ISA> array, trying to find the method in one of the superclasses. The only difference between a class method and an instance method is whether the first parameter is an instance (a blessed reference) or a class name (a string). =end original もし Horse::sound が見つからなかったときには、スーパークラスの中でメソッドが 見つかるかどうか C<@Horse::ISA> 配列をたどります。 クラスメソッドとインスタンスメソッドとの違いは、その最初の引数が インスタンス(bless されたリファレンス)なのかクラス名(文字列)なのかという 点だけです。 =head2 Accessing the instance data (インスタンスのデータへのアクセス) =begin original Because we get the instance as the first parameter, we can now access the instance-specific data. In this case, let's add a way to get at the name: =end original 最初の引数としてインスタンスを得ることができるので、 インスタンス固有のデータにアクセスすることができます。 今回は、名前にアクセスする方法を追加してみましょう: { package Horse; @ISA = qw(Animal); sub sound { "neigh" } sub name { my $self = shift; $$self; } } =begin original Inside C, the C<@_> array contains: =end original C の内側では、C<@_> 配列の中身は: ($horse, "some", "unnecessary", "args") =begin original so the C stores C<$horse> into C<$self>. Then, C<$self> gets de-referenced with C<$$self> as normal, yielding C<"Mr. Ed">. =end original なので C は C<$horse> を C<$self> に保管します。 それから C<$self> は通常通り C<$$self> でデリファレンスされ、C<"Mr. Ed"> と なります。 =begin original It's traditional to C the first parameter into a variable named C<$self> for instance methods and into a variable named C<$class> for class methods. =end original インスタンスメソッドでは C<$self> という名前の変数に、クラスメソッドでは C<$class> という名前の変数に最初の引数を C するのは慣習です。 =begin original Then, the following line: =end original それから、以下の行は: print $horse->name, " says ", $horse->sound, "\n"; =begin original outputs: =end original 以下を出力します: Mr. Ed says neigh. =head2 How to build a horse (馬の作り方) =begin original Of course, if we constructed all of our horses by hand, we'd most likely make mistakes from time to time. We're also violating one of the properties of object-oriented programming, in that the "inside guts" of a Horse are visible. That's good if you're a veterinarian, but not if you just like to own horses. So, let's have the Horse class handle the details inside a class method: =end original もちろん、すべての馬を手で作っていては時々失敗することもあるでしょう。 また馬の「内臓」が外から見えてしまうのはオブジェクト指向 プログラミングの約束事を一つ破っています。 もしあなたが獣医であればそれもよいでしょうが、自分の馬を持ちたいだけであれば そうではありません。 なので Horse クラスのクラスメソッドの内部の扱いを見てみましょう: { package Horse; @ISA = qw(Animal); sub sound { "neigh" } sub name { my $self = shift; # instance method, so use $self $$self; } sub named { my $class = shift; # class method, so use $class my $name = shift; bless \$name, $class; } } =begin original Now with the new C method, we can build a horse as follows: =end original 以下のように、この新しく作った C メソッドで馬を作ることができます: my $horse = Horse->named("Mr. Ed"); =begin original Notice we're back to a class method, so the two arguments to C are C and C. The C operator not only blesses C<\$name>, it also returns that reference. =end original ここで私たちはクラスメソッドに戻っていることに注意してください; また C の2つの引数は C および C になります。 C 演算子は C<\$name> を bless するだけでなく、そのリファレンスを 返します。 =begin original This C method is called a "constructor". =end original この C メソッドは「コンストラクタ」と呼ばれます。 =begin original We've called the constructor C here, so that it quickly denotes the constructor's argument as the name for this particular C. You can use different constructors with different names for different ways of "giving birth" to the object (like maybe recording its pedigree or date of birth). However, you'll find that most people coming to Perl from more limited languages use a single constructor named C, with various ways of interpreting the arguments to C. Either style is fine, as long as you document your particular way of giving birth to an object. (And you I going to do that, right?) =end original ここではコンストラクタを C としたので、このコンストラクタの引数が 特定の C の名前ということを示しています。 (家系や誕生日を記録するといった)違った方法でオブジェクトに「命を吹き込む」 別のコンストラクタにはまた違った名前をつけることができます。 しかし、もっと制限の課せられていた言語から Perl へと来たほとんどの人々は C という一つのコンストラクタに、様々な引数の処理方法を加えて使います。 どちらの方法でも、オブジェクトを作り出すあなたの特定のやり方をあなたが ドキュメント化している限りは問題ありません。 (そしてそれを行って I<きている>、そうですよね?) =head2 Inheriting the constructor (コンストラクタの継承) =begin original But was there anything specific to C in that method? No. Therefore, it's also the same recipe for building anything else that inherited from C, so let's put C and C there: =end original でもこのメソッドに C 特有のことってありますか? 答えは No です。 従って、C から継承して何かを構築するのと同じレシピを使うことが できます; ここに C と C を置いてみましょう: { package Animal; sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n"; } sub name { my $self = shift; $$self; } sub named { my $class = shift; my $name = shift; bless \$name, $class; } } { package Horse; @ISA = qw(Animal); sub sound { "neigh" } } =begin original Ahh, but what happens if we invoke C on an instance? =end original あぁ、でもインスタンスに対して C を呼び出したらどうなるのでしょう? my $horse = Horse->named("Mr. Ed"); $horse->speak; =begin original We get a debugging value: =end original これはデバッグ情報になります: a Horse=SCALAR(0xaca42ac) goes neigh! =begin original Why? Because the C routine is expecting a classname as its first parameter, not an instance. When the instance is passed in, we'll end up using a blessed scalar reference as a string, and that shows up as we saw it just now. =end original なぜこうなってしまうのでしょう? それは、この C ルーチンはその最初の引数には インスタンスではなくクラス名が来ると思っているからです。 インスタンスが渡されるとブレスされたスカラリファレンスを文字列として 使うことになってしまい、それが先ほど見たものになってしまうのです。 =head2 Making a method work with either classes or instances (メソッドをクラスでもインスタンスでも動作できるようにする) =begin original All we need is for a method to detect if it is being called on a class or called on an instance. The most straightforward way is with the C operator. This returns a string (the classname) when used on a blessed reference, and an empty string when used on a string (like a classname). Let's modify the C method first to notice the change: =end original 今必要なことは、クラスに対して呼ばれたのかそれともインスタンスに対して 呼ばれたのかを区別する方法です。 一番率直な方法は C 演算子を使うことです。 これは bless されたリファレンスに対して使うと文字列(クラス名)を返し、 (クラス名のような)文字列に対して使うと空文字列を返します。 ではまず変わったことがわかるように C メソッドを変更してみましょう。 sub name { my $either = shift; ref $either ? $$either : "Any $either"; } =begin original Here, the C operator comes in handy to select either the dereference or a derived string. Now we can use this with either an instance or a class. Note that I've changed the first parameter holder to C<$either> to show that this is intended: =end original ここで C 演算子はでリファレンスするか派生された文字列かを簡単に 選択するために使っています。 さてこれでこのメソッドをインスタンスでもクラスでも使えるようにできました。 最初のパラメータを保持する変数の名前を使う意図に合わせて C<$either> に 変更しています: my $horse = Horse->named("Mr. Ed"); print Horse->name, "\n"; # prints "Any Horse\n" print $horse->name, "\n"; # prints "Mr Ed.\n" =begin original and now we'll fix C to use this: =end original そして C もこれを使うように直してみましょう: sub speak { my $either = shift; print $either->name, " goes ", $either->sound, "\n"; } =begin original And since C already worked with either a class or an instance, we're done! =end original そして C は既にクラスでもインスタンスでも動作するように なっているので、これで完了です! =head2 Adding parameters to a method (メソッドにパラメータを追加する) =begin original Let's train our animals to eat: =end original 次は私たちの動物に食べることをしつけてみましょう: { package Animal; sub named { my $class = shift; my $name = shift; bless \$name, $class; } sub name { my $either = shift; ref $either ? $$either : "Any $either"; } sub speak { my $either = shift; print $either->name, " goes ", $either->sound, "\n"; } sub eat { my $either = shift; my $food = shift; print $either->name, " eats $food.\n"; } } { package Horse; @ISA = qw(Animal); sub sound { "neigh" } } { package Sheep; @ISA = qw(Animal); sub sound { "baaaah" } } =begin original And now try it out: =end original そして試してみます: my $horse = Horse->named("Mr. Ed"); $horse->eat("hay"); Sheep->eat("grass"); =begin original which prints: =end original これは次のように出力します: Mr. Ed eats hay. Any Sheep eats grass. =begin original An instance method with parameters gets invoked with the instance, and then the list of parameters. So that first invocation is like: =end original パラメータを持ったインスタンスメソッドは、そのインスタンスとパラメータの リストとともに呼び出されます。 そのため最初の呼び出しは次のようになります: Animal::eat($horse, "hay"); =head2 More interesting instances (もっと面白いインスタンス) =begin original What if an instance needs more data? Most interesting instances are made of many items, each of which can in turn be a reference or even another object. The easiest way to store these is often in a hash. The keys of the hash serve as the names of parts of the object (often called "instance variables" or "member variables"), and the corresponding values are, well, the values. =end original インスタンスにもっとデータがほしくなったらどうすればよいでしょう? たいていの面白いインスタンスはそれぞれがリファレンスや他の オブジェクトだったりする多くの要素で構成されています。 これらを格納する一番簡単な方法はハッシュを使うことです。 ハッシュのキーはオブジェクトの部品(「インスタンス変数」若しくは 「メンバ変数」と呼ばれます)の名前として提供され、それに対応する値は、まぁ、 その値です。 =begin original But how do we turn the horse into a hash? Recall that an object was any blessed reference. We can just as easily make it a blessed hash reference as a blessed scalar reference, as long as everything that looks at the reference is changed accordingly. =end original でも馬をハッシュにするにはどうしたらよいでしょう? オブジェクトはブレスされた任意のリファレンスであるということを 思い出してください。 リファレンスを参照している箇所を適切に修正すれば、bless された スカラリファレンスと同じように簡単に、それを bless された ハッシュリファレンスで作ることができます。 =begin original Let's make a sheep that has a name and a color: =end original では羊を名前と色を持つようにしてみましょう: my $bad = bless { Name => "Evil", Color => "black" }, Sheep; =begin original so C<< $bad->{Name} >> has C, and C<< $bad->{Color} >> has C. But we want to make C<< $bad->name >> access the name, and that's now messed up because it's expecting a scalar reference. Not to worry, because that's pretty easy to fix up. =end original これで C<< $bad->{Name} >> は C になり、C<< $bad->{Color} >> は C になります。 でも C<< $bad->name >> でその名前にアクセスできるようにしたいですが、それは スカラリファレンスを前提にしているので台無しにされています。 でも心配しないでください、これはとっても簡単に直ります。 =begin original One solution is to override C and C by defining them anew in C, but then any methods added later to C might still mess up, and we'd have to override all of those too. Therefore, it's never a good idea to define the data layout in a way that's different from the data layout of the base classes. In fact, it's a good idea to use blessed hash references in all cases. Also, this is why it's important to have constructors do the low-level work. So, let's redefine C: =end original 一つの解法は C で新しく定義することで C と C をオーバーライドすることですが、後から C に 追加されたメソッドではやはり混乱することになり、それらに全てについても オーバーライドする必要があります。 従って、基底クラスのデータ配置と異なるデータ配置を定義するのは決してよい 方法ではありません。 実際、全ての場合で bless されたハッシュを使うのが良い考えです。 また、これは低レベルの作業を行うコンストラクトが重要な理由です。 それでは、C を再定義しましょう: ## in Animal sub name { my $either = shift; ref $either ? $either->{Name} : "Any $either"; } sub named { my $class = shift; my $name = shift; my $self = { Name => $name }; bless $self, $class; } =begin original Of course, we still need to override C in order to handle constructing a C with a certain color: =end original もちろん、特定の色の C を構築するためにはまだ C を オーバーライドする必要があります: ## in Sheep sub named { my ($class, $name) = @_; my $self = $class->SUPER::named(@_); $$self{Color} = $class->default_color; $self } =begin original (Note that C<@_> contains the parameters to C.) =end original (C<@_> は C への引数を含んでいることに注意してください。) =begin original What's this C? Well, if C has only the name, we still need to set a color, so we'll have a class-specific default color. For a sheep, we might define it as white: =end original この C って何でしょう? C が名前だけで呼ばれても色を設定する必要があります; そこでクラス毎に デフォルトの色を持てるようにしています。 羊には白を定義しておきましょう: ## in Sheep sub default_color { "white" } =begin original Now: =end original それでこれは: my $sheep = Sheep->named("Bad"); print $sheep->{Color}, "\n"; =begin original outputs: =end original 以下を出力します: white =begin original Now, there's nothing particularly specific to C when it comes to color, so let's remove C and implement C to handle color instead: =end original これで、色に関しては C に特有なことは何もなくなったので、 C を削除して代わりに色を扱うために C を 実装しましょう: ## in Animal sub named { my ($class, $name) = @_; my $self = { Name => $name, Color => $class->default_color }; bless $self, $class; } =begin original And then to keep from having to define C for each additional class, we'll define a method that serves as the "default default" directly in C: =end original そして追加したそれぞれのクラスで C を定義する必要が ないように、「デフォルトのデフォルト」を提供するメソッドを C で直接 定義しておきます: ## in Animal sub default_color { "brown" } =begin original Of course, because C and C were the only methods that referenced the "structure" of the object, the rest of the methods can remain the same, so C still works as before. =end original もちろん、C と C だけがオブジェクトの「構造」を 参照していたので、残りのメソッドはそのままにしておくことができます; C は前のままでそのまま動作します。 =head2 A horse of a different color (違った色の馬) =begin original But having all our horses be brown would be boring. So let's add a method or two to get and set the color. =end original でも私たちの馬の全部が全部茶色では飽きてしまいます。 なので色を取得/設定するためのメソッドを一つか二つ作ってみましょう。 ## in Animal sub color { $_[0]->{Color} } sub set_color { $_[0]->{Color} = $_[1]; } =begin original Note the alternate way of accessing the arguments: C<$_[0]> is used in-place, rather than with a C. (This saves us a bit of time for something that may be invoked frequently.) And now we can fix that color for Mr. Ed: =end original 引数にアクセスするための別の方法に関する補足: C<$_[0]> は C をせずにすぐにに使うことができます。 (これは頻繁に呼び出される箇所で時間を節約することができます。) さてこれで Mr. Ed の色を変えることができます: my $horse = Horse->named("Mr. Ed"); $horse->set_color("black-and-white"); print $horse->name, " is colored ", $horse->color, "\n"; =begin original which results in: =end original これは次の結果になります: Mr. Ed is colored black-and-white =head2 Summary (まとめ) =begin original So, now we have class methods, constructors, instance methods, instance data, and even accessors. But that's still just the beginning of what Perl has to offer. We haven't even begun to talk about accessors that double as getters and setters, destructors, indirect object notation, overloading, "isa" and "can" tests, the C class, and so on. That's for the rest of the Perl documentation to cover. Hopefully, this gets you started, though. =end original さて、これまでにクラスメソッド、コンストラクタ、インスタンスメソッド、 インスタンスデータ、そしてアクセッサをも見てきました。 しかしこれらは Perl の提供しているもののまだ始まりにすぎません。 まだゲッター(getter)でありセッター(setter)でもあるアクセッサやデストラクタ、 間接オブジェクト表記、オーバーロード、"isa" および "can" によるテスト、 C クラス、等々についてはまだ話し始めてもいません。 これらは他の Perl ドキュメントでカバーされています。 願わくば、これがあなたの一歩となりますように。 =head1 SEE ALSO =begin original For more information, see L (for all the gritty details about Perl objects, now that you've seen the basics), L (the tutorial for those who already know objects), L (dealing with class data), L (for some more tricks), and books such as Damian Conway's excellent I. =end original もっと詳しい情報は、 L (ここで基礎を見た、Perl オブジェクトに関するすべての強固な詳細)、 L (オブジェクトを知っている人のためのチュートリアル)、 L (クラスデータの取り扱い)、 L (もっとトリッキーなこととか)、 そして Damian Conway の優秀な I 等の書籍を 参照してください。 =begin original Some modules which might prove interesting are Class::Accessor, Class::Class, Class::Contract, Class::Data::Inheritable, Class::MethodMaker and Tie::SecureHash =end original おもしろさを垣間見れるモジュールとして、Class::Accessor, Class::Class, Class::Contract, Class::Data::Inheritable, Class::MethodMaker, Tie::SecureHash。 =head1 COPYRIGHT Copyright (c) 1999, 2000 by Randal L. Schwartz and Stonehenge Consulting Services, Inc. Copyright (c) 2009 by Michael F. Witten. Permission is hereby granted to distribute this document intact with the Perl distribution, and in accordance with the licenses of the Perl distribution; derived documents must include this copyright notice intact. Portions of this text have been derived from Perl Training materials originally appearing in the I course taught by instructors for Stonehenge Consulting Services, Inc. and used with permission. Portions of this text have been derived from materials originally appearing in I and used with permission. =begin meta Transrate: 山科 氷魚 (YAMASHINA Hio) Update: Kentaro Shirakata (5.10.0-) Status: completed =end meta