實例解析Perl繼承用法
本文和大家重點討論一下Perl繼承的概念和用法,繼承簡單的說就是一個類繼承另一個類后,可以使用被繼承類的方法。希望本文的介紹能讓你有所收獲。
Perl繼承
類方法通過@ISA數組Perl繼承,變量的Perl繼承必須明確設定。下例創建兩個類Bean.pm和Coffee.pm,其中Coffee.pmPerl繼承Bean.pm的一些功能。此例演示如何從基類(或稱超類)Perl繼承實例變量,其方法為調用基類的構造函數并把自己的實例變量加到新對象中。
Bean.pm代碼如下:
- packageBean;
- requireExporter;
- @ISA=qw(Exporter);
- @EXPORT=qw(setBeanType);
- subnew{
- my$type=shift;
- my$this={};
- $this->{'Bean'}='Colombian';
- bless$this,$type;
- return$this;
- }
- #
- #Thissubroutinesetstheclassname
- subsetBeanType{
- my($class,$name)=@_;
- $class->{'Bean'}=$name;
- print"Setbeanto$name\n";
- }
- 1;
此類中,用$this變量設置一個匿名哈希表,將'Bean'類型設為'Colombian'。方法setBeanType()用于改變'Bean'類型,它使用$class引用獲得對對象哈希表的訪問。
Coffee.pm代碼如下:
- 1#
- 2#TheCoffee.pmfiletoillustrateinheritance.
- 3#
- 4packageCoffee;
- 5requireExporter;
- 6requireBean;
- 7@ISA=qw(Exporter,Bean);
- 8@EXPORT=qw(setImports,declareMain,closeMain);
- 9#
- 10#setitem
- 11#
- 12subsetCoffeeType{
- 13my($class,$name)=@_;
- 14$class->{'Coffee'}=$name;
- 15print"Setcoffeetypeto$name\n";
- 16}
- 17#
- 18#constructor
- 19#
- 20subnew{
- 21my$type=shift;
- 22my$this=Bean->new();#####<-LOOKHERE!!!####
- 23$this->{'Coffee'}='Instant';#unlesstoldotherwise
- 24bless$this,$type;
- 25return$this;
- 26}
- 271;
第6行的requireBean;語句包含了Bean.pm文件和所有相關函數,方法setCoffeeType()用于設置局域變量$class->{'Coffee'}的值。在構造函數new()中,$this指向Bean.pm返回的匿名哈希表的指針,而不是在本地創建一個,下面兩個語句分別為創建不同的哈希表從而與Bean.pm構造函數創建的哈希表無關的情況和Perl繼承的情況:
my$this={};#非Perl繼承
my$this=$theSuperClass->new();#Perl繼承
下面代碼演示如何調用Perl繼承的方法:
- 1#!/usr/bin/perl
- 2push(@INC,'pwd');
- 3useCoffee;
- 4$cup=newCoffee;
- 5print"\n--------------------Initialvalues------------\n";
- 6print"Coffee:$cup->{'Coffee'}\n";
- 7print"Bean:$cup->{'Bean'}\n";
- 8print"\n--------------------ChangeBeanType----------\n";
- 9$cup->setBeanType('Mixed');
- 10print"BeanTypeisnow$cup->{'Bean'}\n";
- 11print"\n------------------ChangeCoffeeType----------\n";
- 12$cup->setCoffeeType('Instant');
- 13print"Typeofcoffee:$cup->{'Coffee'}\n";
該代碼的結果輸出如下:
- --------------------Initialvalues------------
- Coffee:Instant
- Bean:Colombian
- --------------------ChangeBeanType----------
- SetbeantoMixed
- BeanTypeisnowMixed
- ------------------ChangeCoffeeType----------
- SetcoffeetypetoInstant
- Typeofcoffee:Instant
上述代碼中,先輸出對象創建時哈希表中索引為'Bean'和'Coffee'的值,然后調用各成員函數改變值后再輸出。
【編輯推薦】