=head1 NAME perlboot - Beginner's Object-Oriented Tutorial J<< ja/perlboot - Perl オブジェクト指向導入編 >> =head1 DESCRIPTION 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. J<< ja/ 他の言語でオブジェクトに親しんでいたのでなければ, 他の Perl オブジェクトのドキュメントのいくつかは気力をくじかせるでしょう. オブジェクトを使うための基本的なリファレンス L, Perl のオブジェクトシステムの特性のチュートリアル的な紹介 L 等のように. >> 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. J<< ja/ そこで, 別のアプローチをとってみましょう. オブジェクトの経験がないことを前提にしましょう. もし, サブルーティン(L)や, リファレンス(L等), パッケージ(L) を知っているのならそれが役に立つでしょう. もしまだわからなければまずそちらを先に知っておくべきでしょう. >> =head2 If we could talk to the animals... J<< ja/もし動物と会話できたら... >> Let's let the animals talk for a moment: J<< ja/動物さんたちにちょっとしゃべってもらいましょう. >> 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; This results in: J<< ja/これは次の結果を得ます: >> a Cow goes moooo! a Horse goes neigh! a Sheep goes baaaah! Nothing spectacular here. Simple subroutines, albeit from separate packages, and called using the full package name. So let's create an entire pasture: J<< ja/ 目新しいコトはありません. 別々のパッケージに分かれていて 完全なパッケージ名を使って呼び出していますが, 単なるサブルーティンです. では, 牧場を作ってみましょう. >> # Cow::speak, Horse::speak, Sheep::speak as before @pasture = qw(Cow Cow Horse Sheep Sheep); foreach $animal (@pasture) { &{$animal."::speak"}; } This results in: J<< ja/これは次の結果を得ます: >> a Cow goes moooo! a Cow goes moooo! a Horse goes neigh! a Sheep goes baaaah! a Sheep goes baaaah! 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. J<< ja/ うわ. シンボリックcoderefのデリファレンスがあります. かなり粗雑です. C モードも考えてみると, 大きなプログラムには全然向きません. なぜその様なものが必要とされるのでしょう? それはパッケージ名を, そのパッケージの呼び出そうとしている サブルーティンの名前から分離できないからです. ("Cow::speek" というメソッド名が必要だから.) >> Or is it? J<< ja/ではどうしましょう? >> =head2 Introducing the method invocation arrow J<< ja/メソッド呼び出しの矢印 >> 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: J<<<< ja/ いまのところ, C<< Class->method >> は C パッケージの C サブルーティンを呼び出すとだけ言っておきましょう. (ここで "Class" は "カテゴリ" の意味です. "学級" ではありません.) 厳密には完全ではありませんが, 少しずつ進めていきましょう. これは次のように使います: >>>> # Cow::speak, Horse::speak, Sheep::speak as before Cow->speak; Horse->speak; Sheep->speak; And once again, this results in: J<< ja/ そしてこれは次の結果を得ます: >> a Cow goes moooo! a Horse goes neigh! a Sheep goes baaaah! That's not fun yet. Same number of characters, all constant, no variables. But yet, the parts are separable now. Watch: J<< ja/ 別におもしろくもありませんね. 同じ文字数ですし全て定数で変数もありません. でも, 今度はパッケージ名を分離できるのです. 次を見てください: >> $a = "Cow"; $a->speak; # invokes Cow->speak 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. J<< ja/ 関数名からパッケージ名を分けれるので, パッケージ名に変数を使うことができるのです! そして今度は C が有効であってもちゃんと機能するのです. >> =head2 Invoking a barnyard J<< ja/裏庭の呼び出し >> Let's take that new arrow invocation and put it back in the barnyard example: J<< ja/ 新しい矢印呼び出しを使ってみましょう. そして裏庭の例に戻してみましょう. >> 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; } There! Now we have the animals all talking, and safely at that, without the use of symbolic coderefs. J<< ja/ みんなちゃんとしゃべってくれます! また今度はシンボリックcoderefを使っていなくて安全です. >> 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. J<< ja/ でも, コードをよく見てみると, 各 C 関数はよく似た構造を持っています. C 演算子と, 2語を除くと同一のテキストを含んでいるだけです. 共通箇所を分解するのはよいことです. 例えば, 後で全ての C を C に変えることもできるようになります. >> 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. J<< ja/ また, 大騒ぎすることなくそれを行う方法も実際あります. しかし, メソッド呼び出しの矢印が何を行ってくれているのかについて ここで少し知っておかなければなりません. >> =head2 The extra parameter of method invocation J<< ja/メソッド呼び出しの追加パラメータ >> The invocation of: J<< ja/メソッド呼び出し: >> Class->method(@args) attempts to invoke subroutine C as: J<< ja/は, C 関数を次のように呼び出すそうとします: >> Class::method("Class", @args); (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: J<< ja/ (もし関数を見つけることができなかったときには, "継承" が走査されます. これに関してはあとで説明します.) これは最初のパラメータとしてクラス名を得ることを意味します. (もし引数がなければそれがただ1つのパラメータになります.) このことから C のおしゃべり関数を次のように書き改めることができます. >> sub Sheep::speak { my $class = shift; print "a $class goes baaaah!\n"; } And the other two animals come out similarly: J<< ja/ また他の動物たちも同様になります. >> sub Cow::speak { my $class = shift; print "a $class goes moooo!\n"; } sub Horse::speak { my $class = shift; print "a $class goes neigh!\n"; } 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. J<< ja/ それぞれにおいて C<$class> にはその関数の特定の値を得ます. しかしもう一度考え直してみると, かなりよく似た構造になったいます. さらに分離することはできないでしょうか? それは同じクラスの別のメソッドを呼ぶことで可能です. >> =head2 Calling a second method to simplify things J<< ja/簡単に2つ目のメソッドを呼び出す >> Let's call out from C to a helper method called C. This method provides the constant text for the sound itself. J<< ja/ C から補助メソッド C よ呼び出してみましょう. このメソッドはその鳴き声として固定文字列を提供します. >> { package Cow; sub sound { "moooo" } sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n" } } 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? J<<<< ja/ さて, 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" } } 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! J<< ja/ パッケージ名と鳴き声の指定だけが変わりました. ところで Cow と Horse で C の定義を共有する方法はないでしょうか? それが継承です! >> =head2 Inheriting the windpipes J<< ja/気管を継承する >> We'll define a common subroutine package called C, with the definition for C: J<< ja/ 共通の関数のパッケージとして C を作ります. ここで C を定義します. >> { package Animal; sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n" } } Then, for each animal, we say it "inherits" from C, along with the animal-specific sound: J<< ja/ 次に各動物たちに対して, それぞれの鳴き声の定義と一緒に C から "派生" するように言います. >> { package Cow; @ISA = qw(Animal); sub sound { "moooo" } } Note the added C<@ISA> array. We'll get to that in a minute. J<< ja/ ここで, C<@ISA> 配列が加えられていることに注意してください. 少々これについて説明します. >> But what happens when we invoke C<< Cow->speak >> now? J<<<< ja/ とことでここで C<< Cow->speak >> を呼び出すとなにが起こるのでしょう? >>>> 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. J<< ja/ まず, Perl が引数リストを構築します. 今回は単純に C だけです. それから Perl は C を探します. しかしそれはありません. そのため Perl は継承配列 C<@Cow::ISA> を調べます. それは存在し, 名前を1つ C を格納しています. >> 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. J<< ja/ Perl は次に C の C を C の様に調べます. 今度は見つかりました. そこで Perl はこの関数をさっき作っておいた引数リストで呼び出します. >> 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! J<< ja/ C 関数においては, C<$class> は C になります (これが1つめの引数です). そのため C<< $class->sound >> の呼び出しにおいて C<< Cow->sound >> を得ます. 最初は C<@ISA> を探すことなく調べます. そしてこれは成功します. >> =head2 A few notes about @ISA J<< ja/@ISAに関して追記 >> This magical C<@ISA> variable (pronounced "is a" not "ice-uh"), 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. J<< ja/ この魔法の C<@ISA> 変数 ( "アイサ"ではなく"イズ-ア") は, C が C の"一種である(is-a)" と宣言している. これが単なる1つの値ではなく配列であることに注意してください. 稀ではありますが, メソッドが見つからなかったときに探す親クラスを 1つ以上もつこともあるためです. >> 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>. Typically, each C<@ISA> has only one element (multiple elements means multiple inheritance and multiple headaches), so we get a nice tree of inheritance. J<< ja/ もし C も C<@ISA> をもっていたらそれも同様に調べられます. 検索は C<@ISA> の中を再帰的に, 深さ優先, 左から右に行われます. 典型的に, 各 C<@ISA> がただ1つのみ要素を持っています. そのため良好な継承ツリーを得ます. (複数の要素を持っていれば複数の継承, 複数の難問を持っています.) >> 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. J<< ja/ C を有効にしたとき, C<@ISA> は明示的なパッケージ名を 持っていないため, そしてレキシカル変数 ("my") でもないため警告を受けます. この変数はレキシカル変数にはできません. (継承メカニズムが探索できるように, パッケージに属していなければなりません.) これに対処する方法は2つあります. >> The easiest is to just spell the package name out: J<< ja/ 一番簡単な方法はパッケージ名をつけて使うことです. >> @Cow::ISA = qw(Animal); Or allow it as an implicitly named package variable: J<< ja/もしくは暗黙に名付けられたパッケージ変数を許可することです. >> package Cow; use vars qw(@ISA); @ISA = qw(Animal); If you're bringing in the class from outside, via an object-oriented module, you change: J<< ja/ もしオブジェクト指向モジュールを通して外部からクラスに持ち込むのなら, >> package Cow; use Animal; use vars qw(@ISA); @ISA = qw(Animal); into just: J<< ja/これを次のように変更します. >> package Cow; use base qw(Animal); And that's pretty darn compact. J<< ja/ずいぶんコンパクトになります. >> =head2 Overriding the methods J<< ja/メソッドのオーバーライド >> Let's add a mouse, which can barely be heard: J<< ja/ねずみを追加してみましょう. その声は微かでしょう. >> # 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; which results in: J<< ja/これは次のようになります. >> a Mouse goes squeak! [but you can barely hear it!] 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 didn't even need to say that a C was an C at all, since all of the methods needed for C are completely defined with C. J<<<< ja / ここでは C は C<< Animal->speak >> を呼ぶのではなく 自分用のおしゃべりルーティン C<< Mouse->speak >> を持っています. これは, "オーバーライド" と呼ばれています. 事実, C が C の一種であるという必要はまったくありません. おしゃべり(C)に必要なメソッドは全て C に定義されています. >>>> But we've now duplicated some of the code from C<< Animal->speak >>, and this can once again be a maintenance headache. So, can we avoid that? Can we say somehow that a C does everything any other C does, but add in the extra comment? Sure! J<< ja/ しかしそれでもいくらかのコードを C<< Animal->speak >> から写しています. これはまたメンテナンスの悩みを再現させています. この悩みを回避することはできないでしょうか? C が行っていることを C でも, 少々コメントを追加して 行う方法はないでしょうか? もちろんあります! >> First, we can invoke the C method directly: J<< ja/ まず 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"; } } Note that we have to include the C<$class> parameter (almost surely the value of C<"Mouse">) as the first parameter to C, since we've stopped using the method arrow. Why did we stop? Well, if we invoke C<< Animal->speak >> there, the first parameter to the method will be C<"Animal"> not C<"Mouse">, and when time comes for it to call for the C, it won't have the right class to come back to this package. J<<<< ja/ メソッド矢印をやめたために, C の1つめの引数として C<$class> パラメータ(おそらくは C<"Mouse"> という値 )を含めなければ いけないことに注意してください. なぜやめてしまったのでしょう? ええ, もしここで C<< Animal->speak >> と呼び出せば最初のパラメータは C<"Mouse"> ではなく C<"Animal"> になってしまいます. そして C が呼び出されたときに正しくこのクラスに戻ってくることが できなくなってしまうのです. >>>> Invoking C directly is a mess, however. What if C didn't exist before, and was being inherited from a class mentioned in C<@Animal::ISA>? Because we are no longer using the method arrow, we get one and only one chance to hit the right subroutine. J<< ja/ しかし C を直接呼び出すのはいまいちです. もし C が存在せず, C<@Animal::ISA> に 指定されるクラスから継承していたらどうなるのでしょう? メソッド矢印をすでに使っていないために正しくサブルーティンを探し当てる チャンスはこの方法しかなくなってしまっているのです. >> Also note that the C classname is now hardwired into the subroutine selection. This is a mess if someone maintains the code, changing C<@ISA> for C and didn't notice C there in C. So, this is probably not the right way to go. J<< ja/ C クラス名が関数の中に書き込まれていることにも注意してください. もしだれかがコードを修正し, C のにある C に気付かないまま C の C<@ISA> を書き換えてしまったらまずいことになります. 結局, これは適切な方法ではないのです. >> =head2 Starting the search from a different place J<< ja/異なる場所から探索を始める >> A better solution is to tell Perl to search from a higher place in the inheritance chain: J<< ja/ より望ましい解法は Perl に継承ツリーのより高位から探索することを Perl に伝えることです: >> # 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"; } } Ahh. This works. Using this syntax, we start with C to find C, and use all of C's inheritance chain if not found immediately. And yet the first parameter will be C<$class>, so the found C method will get C as its first entry, and eventually work its way back to C for the details. J<< ja/ これはちゃんと動作します. この構文を使うことで, C の探索を C から開始することができます. そして C に直接見つからなくても C の全ての継承連鎖を使う ことができます. さらに, 1つめのパラメータは C<$class> になるため 見つかった C メソッドでは1つめのエントリに C を得て, ついに C に戻って動作する様になります. >> But this isn't the best solution. We still have to keep the C<@ISA> and the initial search package coordinated. Worse, if C had multiple entries in C<@ISA>, we wouldn't necessarily know which one had actually defined C. So, is there an even better way? J<< ja/ しかしこれはまだ最良の解ではありません. C<@ISA> と同等の最初の探索パッケージを維持しなければなりません. さらに悪いことに C が C<@ISA> に複数のエントリを持っていたら 実際に C を定義しているのがどれなのかわかりません. もっと良い方法はないでしょうか? >> =head2 The SUPER way of doing things J<< ja/SUPER 解答 >> By changing the C class to the C class in that invocation, we get a search of all of our super classes (classes listed in C<@ISA>) automatically: J<< ja/ 呼び出し時の C クラスを C クラスに変えることで 検索を自動的に全ての基底クラス群(C<@ISA> に記述されているクラス群) に対して行うことができます. >> # 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"; } } So, C means look in the current package's C<@ISA> for C, invoking the first one found. Note that it does I look in the C<@ISA> of C<$class>. J<< ja/ つまり, C は現在のパッケージの C<@ISA> から C を探し, 最初に見つかったものを呼び出します. これは C<$class> の C<@ISA> はI<見ない>点に注意してください. >> =head2 Where we're at so far... J<< ja/現在地点 >> So far, we've seen the method arrow syntax: J<< ja/ これまでに見てきたものは, メソッド矢印構文: >> Class->method(@args); or the equivalent: J<< ja/その等価な文: >> $a = "Class"; $a->method(@args); which constructs an argument list of: J<< ja/構築される引数リスト: >> ("Class", @args) and attempts to invoke J<< ja/呼び出され方 >> Class::method("Class", @Args); However, if C is not found, then C<@Class::ISA> is examined (recursively) to locate a package that does indeed contain C, and that subroutine is invoked instead. J<< ja/ しかし, C が見つからなければ C<@Class::ISA> が(再帰的に) 実際 C を含んでいるパッケージを探すために使われます. >> 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, and provide a nice way to reuse implementations with variations. This is at the core of what objects provide, but objects also provide instance data, which we haven't even begun to cover. J<< ja/ この簡単な構文を使うことでクラスメソッド, (複数の)継承, オーバーライド, そして拡張を行えるようになりました. これまでに見てきたもの丈で共通処理を抽出し, 様々な実装に再利用する 良好な方法を提供することができます. これはオブジェクトが提供するものの核心です. とはいえオブジェクトはこれ以外にもまだ説明していませんが インスタンスデータも提供します. >> =head2 A horse is a horse, of course of course -- or is it? J<< ja/馬は馬, もちろん -- ですか? >> Let's start with the code for the C class and the C class: J<< ja/ C クラスと C クラスを書いてみましょう. >> { package Animal; sub speak { my $class = shift; print "a $class goes ", $class->sound, "!\n" } } { package Horse; @ISA = qw(Animal); sub sound { "neigh" } } 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: J<<<< ja/ C<< Horse->speak >> を呼び出すことで C に渡り, そこから C に鳴き声を作りに戻ります. 結果は次のようになります: >>>> a Horse goes neigh! But all of our Horse objects would have to be absolutely identical. If I add a subroutine, all horses automatically share it. That's great for making horses the same, but how do we capture the distinctions about an individual horse? For example, suppose I want to give my first horse a name. There's got to be a way to keep its name separate from the other horses. J<< ja/ しかしこのすべての Horse オブジェクトは完全に同一です. サブルーティンを追加しても, 全ての馬が自動的にそれを共有します. 同じ馬を作るが目的ならすばらしいことですが, 個々の馬を識別したい時にはどうすれば良いのでしょうか? 例えば最初の馬に名前を付けたい時にはどうすれば良いのでしょう. もちろん, それぞれの馬の名前を分離して維持する方法があります. >> We can do that by drawing a new distinction, called an "instance". An "instance" is generally created by a class. 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. J<< ja/ "インスタンス"と呼ばれる新しい区別を使うことでそれを行うことができます. "インスタンス” は一般的にクラスに生成されます. Perl では任意のリファレンスならインスタンスになることができます. そこでまず単純なリファレンスとして, 馬の名前を保持するスカラーリファレンス を使ってみましょう. >> my $name = "Mr. Ed"; my $talking = \$name; So now C<$talking> is a reference to what will be the instance-specific data (the name). The final step in turning this into a real instance is with a special operator called C: J<< ja/ これで C<$talking> はインスタンス指向のデータ(名前)のリファレンスになりました. これを実際のインスタンスにする最後のステップは C と呼ばれる 特別な操作です. >> bless $talking, Horse; This operator stores information about the package named C into the thing pointed at by the reference. At this point, we say C<$talking> 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. J<< ja/ これはパッケージ名 C に関する情報を リファレンスに指されているものに格納する操作を行います. これにより, C<$talking> が C のインスタンスになったといいます. これで, 個々の馬を識別できます. リファレンスはそれ以外に変化はありませんし, 伝統的なデリファレンス操作を使うこともできます. >> =head2 Invoking an instance method J<< ja/インスタンスメソッドの呼び出し >> The method arrow can be used on instances, as well as names of packages (classes). So, let's get the sound that C<$talking> makes: J<< ja; メソッド矢印はパッケージ(クラス)名の時と同じように, インスタンスに対しても使うことができます. では, C<$talking> の作り出す音を取り出してみましょう: >> my $noise = $talking->sound; To invoke C, Perl first notes that C<$talking> is a blessed reference (and thus an instance). It then constructs an argument list, in this case from just C<($talking)>. (Later we'll see that arguments will take their place following the instance variable, just like with classes.) J<< ja; C を呼び出すために, Perl は始めに C<$talking> が ブレスされたリファレンス(つまりインスタンス)であることを 確認します. それから引数リストを構成します, 今回は C<($talking)> だけです. (後ほど, クラスの時と 同様にインスタンス変数に続けて引数を置くのも説明します.) >> Now for the fun part: Perl takes the class in which the instance was blessed, in this case C, and uses that to locate the subroutine to invoke the method. In this case, C is found directly (without using inheritance), yielding the final subroutine invocation: J<< ja; さて, ここがおもしろいところです: Perl はインスタンスがブレスされているクラス, 今回は C を取り出し, メソッド呼び出しを 行うための関数の場所を特定するためにそれを使います. 今回は, C が直接に(継承を使うことなしに) みつかり, 最終的に次の関数呼び出しとなります: >> Horse::sound($talking) 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. J<< ja; この最初のパラメータは, 先ほどのようなクラス名ではなく インスタンスのままである点に注意してください. この結果 C を復帰値として受け取り, これが C<$noise> 変数に代入されます. >> If Horse::sound had not been found, we'd be wandering up the C<@Horse::ISA> list to try to find the method in one of the superclasses, just as for a class method. 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). J<< ja; もし Horse::sound が見つからなかったときには, クラスメソッドの時と同じように, スーパークラスの 中でメソッドが見つかるかどうか C<@Horse::ISA> リストをたどります. クラスメソッドと インスタンスメソッドとの違いは その最初の引数がインスタンス(ブレスされたリファレンス) なのかクラス名(文字列)なのかという点だけです. >> =head2 Accessing the instance data J<< ja; インスタンスのデータへのアクセス >> 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: J<< ja; 最初の引数としてインスタンスを得ることが できるので, インスタンス固有のデータにアクセスする ことができます. 今回は, 名前にアクセスする方法を 追加してみましょう: >> { package Horse; @ISA = qw(Animal); sub sound { "neigh" } sub name { my $self = shift; $$self; } } Now we call for the name: J<< ja; これでその名前を呼ぶことができます: >> print $talking->name, " says ", $talking->sound, "\n"; Inside C, the C<@_> array contains just C<$talking>, which the C stores into C<$self>. (It's traditional to shift the first parameter off into a variable named C<$self> for instance methods, so stay with that unless you have strong reasons otherwise.) Then, C<$self> gets de-referenced as a scalar ref, yielding C, and we're done with that. The result is: J<< ja; C の内側では, C<@_> 配列には C で C<$self> に代入される C<$talking> のみが 含まれています. (インスタンスメソッドにおいて, その最初のパラメータを C<$self> という名前の変数に shift して代入するのはお約束です, なのでここでは あまり理由を追い求めないでください.) それから, C<$self> はスカラーリファレンスとして デリファレンスされ, C が取り出され, それでおしまいです. 結果は次のようになります: >> Mr. Ed says neigh. =head2 How to build a horse J<< ja; 馬の作り方 >> 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 let the Horse class build a new horse: J<< ja; もちろん, すべての馬を手で作っていては 時々失敗することもあるでしょう. また馬の"内臓"が 外から見えてしまうのはオブジェクト指向プログラミングの 約束事を1つ破っています. もしあなたが獣医であればそれもよいでしょうが, 自分の馬を持ちたいだけであればそうではありません. なので Horse クラスに新しい馬を作ってもらいましょう: >> { package Horse; @ISA = qw(Animal); sub sound { "neigh" } sub name { my $self = shift; $$self; } sub named { my $class = shift; my $name = shift; bless \$name, $class; } } Now with the new C method, we can build a horse: J<< ja; この新しく作った C メソッドで馬を作ることが できます: >> my $talking = Horse->named("Mr. Ed"); 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 the reference to C<$name>, so that's fine as a return value. And that's how to build a horse. J<< ja; ここで私たちはクラスメソッドに戻っていることに 注意してください, また C の2つの引数は C および C になります. C 演算子は C<$name> をブレスするだけでなく, C<$name> へのリファレンスを返します, それによって これは適切な復帰値となります. これが馬の作り方です. >> 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?) J<< ja; ここではコンストラクタを C としたので, このコンストラクタの引数が特定の C の名前と いうことを示しています. (家系や誕生日を記録するといった)違った方法で オブジェクトに"命を吹き込む"別のコンストラクタには また違った名前をつけることができます. しかし, もっと制限の課せられていた言語から Perl へと来たほとんどの人々は C という 1つのコンストラクタに, 様々な引数の処理方法を 加えて使います. どちらの方法でもオブジェクトを 作り出すあなたの特定のやり方をあなたが ドキュメント化している限りは問題ありません. (そしてそれを行ってI<きている>, そうですよね?) >> =head2 Inheriting the constructor J<< ja; コンストラクタの継承 >> 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 it there: J<< ja; でもこのメソッドに C 特有のことってありますか? 答えは No です. 従って, 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" } } Ahh, but what happens if we invoke C on an instance? J<< ja; あぁ, でもインスタンスに対して C を呼び出したら どうなるのでしょう? >> my $talking = Horse->named("Mr. Ed"); $talking->speak; We get a debugging value: J<< ja; これはデバッグ情報になってしまいます: >> a Horse=SCALAR(0xaca42ac) goes neigh! 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. J<< ja; なぜこうなってしまうのでしょう? それは, この C ルーチンはその最初の 引数にはインスタンスではなくクラス名が来ると思っているからです. インスタンスが渡されるとブレスされたスカラーリファレンスを 文字列として使うことになってしまい, それが先ほどみたものに なってしまうのです. >> =head2 Making a method work with either classes or instances J<< ja; メソッドをクラスでもインスタンスでも動作できるようにする >> 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 C when used on a string (like a classname). Let's modify the C method first to notice the change: J<< ja; 今必要なことは, クラスに対して呼ばれたのか それともインスタンスに対して呼ばれたのかを区別する方法です. 一番率直な方法は C 演算子を使うことです. これはブラスされたリファレンスに対して使うと 文字列(クラス名)を返し, (クラス名のような)文字列に 対して使うと C を返します. (訳注:CはCを返しません, 空文字列('')を返します.) ではまず変わったことがわかるように C メソッドを 変更してみましょう. >> sub name { my $either = shift; ref $either ? $$either # it's an instance, return name : "an unnamed $either"; # it's a class, return generic } 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: J<< ja; ここで C 演算子はでリファレンスするか派生された文字列かを 簡単に選択するために使っています. さてこれでこの メソッドをインスタンスでもクラスでも使えるようにできました. 最初のパラメータを保持する変数の名前を使う意図に合わせて C<$either> に変更しています: >> my $talking = Horse->named("Mr. Ed"); print Horse->name, "\n"; # prints "an unnamed Horse\n" print $talking->name, "\n"; # prints "Mr Ed.\n" and now we'll fix C to use this: J<< ja; そして C もこれを使うように直してみましょう: >> sub speak { my $either = shift; print $either->name, " goes ", $either->sound, "\n"; } And since C already worked with either a class or an instance, we're done! J<< ja; そして C は既にクラスでもインスタンスでも動作する ようになっているので, これで完了です! >> =head2 Adding parameters to a method J<< ja; メソッドにパラメータを追加する >> Let's train our animals to eat: J<< ja; 次は私たちの動物に食べることをしつけてみましょう: >> { package Animal; sub named { my $class = shift; my $name = shift; bless \$name, $class; } sub name { my $either = shift; ref $either ? $$either # it's an instance, return name : "an unnamed $either"; # it's a class, return generic } 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" } } And now try it out: J<< ja; そして試してみます: >> my $talking = Horse->named("Mr. Ed"); $talking->eat("hay"); Sheep->eat("grass"); which prints: J<< ja; これは次のように出力します: >> Mr. Ed eats hay. an unnamed Sheep eats grass. An instance method with parameters gets invoked with the instance, and then the list of parameters. So that first invocation is like: J<< ja; パラメータを持ったインスタンスメソッドは, そのインスタンスとパラメータのリストとともに 呼び出されます. そのため最初の呼び出しは次のようになります: >> Animal::eat($talking, "hay"); =head2 More interesting instances J<< ja; もっと面白いインスタンス >> 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. J<< ja; インスタンスにもっとデータがほしくなったら どうすればよいでしょう? たいていの面白いインスタンスは それぞれがリファレンスやほかのオブジェクトだったり する多くの要素で構成されています. これらを格納する 一番簡単な方法はハッシュを使うことです. ハッシュのキーは オブジェクトの部品("インスタンス変数"若しくは "メンバ変数"と呼ばれます)の名前として提供され, それに対応する値は, まぁ, その値です. >> 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. J<< ja; でも馬をハッシュにするにはどうしたらよいでしょう? オブジェクトはブレスされた任意のリファレンスである ということを思い出してください. リファレンスを参照している箇所を適切に修正すれば, ブレスされたスカラーリファレンスと同じように簡単に それをブレスされたハッシュリファレンスで作ることができます. >> Let's make a sheep that has a name and a color: J<< ja; では羊を名前と色を持つようにしてみましょう: >> my $bad = bless { Name => "Evil", Color => "black" }, Sheep; 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: J<<<< ja; これで C<< $bad->{Name} >> は C になり, C<< $bad->{Color} >> は C になります. でも C<< $bad->name >> でその名前にアクセスできるようにしたい ですが, それはスカラーリファレンスを前提にしているので 台無しにされています. でも心配しないでください, これはとっても簡単に直ります: >>>> ## in Animal sub name { my $either = shift; ref $either ? $either->{Name} : "an unnamed $either"; } And of course C still builds a scalar sheep, so let's fix that as well: J<< ja; そしてもちろん C はスカラーの羊を作っているので これも同じようになおしましょう. >> ## in Animal sub named { my $class = shift; my $name = shift; my $self = { Name => $name, Color => $class->default_color }; bless $self, $class; } 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 initial color. For a sheep, we might define it as white: J<< ja; この C って何でしょう? C が名前だけで呼ばれても色を設定する必要があります, そこでクラス毎に初期値となる色を持てるようにしています. 羊には白を定義しておきましょう: >> ## in Sheep sub default_color { "white" } And then to keep from having to define one for each additional class, we'll define a "backstop" method that serves as the "default default", directly in C: J<< ja; そして追加したそれぞれのクラスで色を定義する必要が ないように, "デフォルトのデフォルト"を提供する "安全ネット"メソッドを C で直接定義しておきます: >> ## in Animal sub default_color { "brown" } Now, 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. J<< ja; そして, C と C だけがオブジェクトの"構造"を 参照していたので, 残りのメソッドはそのままに しておくことができます, C は前のままでそのまま 動作します. >> =head2 A horse of a different color J<< ja; 違った色の馬 >> But having all our horses be brown would be boring. So let's add a method or two to get and set the color. J<< ja; でも私たちの馬の全部が全部茶色では飽きてしまいます. なので色を取得/設定するためのメソッドを1つか2つ作ってみましょう. >> ## in Animal sub color { $_[0]->{Color} } sub set_color { $_[0]->{Color} = $_[1]; } 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: J<< ja; 引数にアクセスするための別の方法に関する補足: C<$_[0]> は C の代わりに in-place に 使うことができます. (これは頻繁に呼び出される箇所で 時間を節約することができます.) さてこれで Mr. Ed の色を変えることができます: >> my $talking = Horse->named("Mr. Ed"); $talking->set_color("black-and-white"); print $talking->name, " is colored ", $talking->color, "\n"; which results in: J<< ja; これは次の結果になります: >> Mr. Ed is colored black-and-white =head2 Summary J<< ja; 要約 >> 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, subclasses that add instance data, per-class data, overloading, "isa" and "can" tests, C class, and so on. That's for the rest of the Perl documentation to cover. Hopefully, this gets you started, though. J<< ja; さて, これまでにクラスメソッド, コンストラクタ, インスタンスメソッド, インスタンスデータ, そして アクセッサをも見てきました. しかしこれらは Perl の提供しているもののまだ始まりにすぎません. まだゲッター(getter)でありセッター(setter)でもある アクセッサやデストラクタ, 間接オブジェクト表記, インスタンスデータを追加するサブクラス, クラス毎のデータ, オーバーロード, "isa" および "can" によるテスト, C クラス, 等々についてはまだ話し始めても いません. これらは他の Perl ドキュメントでカバーされています. 願わくば, これがあなたの一歩となりますように. >> =head1 SEE ALSO 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. J<< ja; もっと詳しい情報は, L (ここで基礎を見た, Perl オブジェクトに関する すべての強固な詳細), L (オブジェクトを知っている人のためのチュートリアル), L (クラスデータの取り扱い), L (もっとトリッキーなこととか), そして Damian Conway の優秀な I 等の書籍. >> Some modules which might prove interesting are Class::Accessor, Class::Class, Class::Contract, Class::Data::Inheritable, Class::MethodMaker and Tie::SecureHash J<< ja; おもしろさを垣間見れるモジュールとして, 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. 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. J<< ja; Copyright (c) 1999, 2000 by Randal L. Schwartz 及び ストーンヘンジコンサルティングサービス. このドキュメントを完全に Perl 配布物で配布するために, そして Perl 配布物のライセンスに従ってここに許可を与えます; 派生したドキュメントはこの著作権表記を完全に含まなけらば なりません. (原文: Copyright (c) 1999, 2000 by Randal L. Schwartz and Stonehenge Consulting Services, Inc. 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. J<< ja; このテキストの一部はストーンヘンジコンサルティングサービス によって講じ(teach)られた I<パッケージ, リファレンス, オブジェクト及びモジュール> コースで最初に作られた Perl トレーニング資料から派生し, 許可を使っています. >> Portions of this text have been derived from materials originally appearing in I and used with permission. J<< ja; このテキストの一部は I で最初に作られた 資料から派生し, 許可を使っています. >> =head1 TRANSALTE TO JAPANESE J<< ja;和訳 >> 山科 氷魚 (YAMASHINA Hio) Original distribution is perl VERSION 5.8.8. Translated on 2003-07-18 (perl-5.8.0). (Updated on 2007-08-07.) J<< ja; 原典: perl VERSION 5.8.8. 翻訳日: 2003-07-18 (perl-5.8.0). (修正: 2007-08-07.) >>