• perl 使用SUPER类来访问覆盖的方法


    有时候,你希望一个衍生类的方法表现得象基类中的某些方法的封装器
    
    
    
    这就是 SUPER 伪类提供便利的地方。它令你能够调用一个覆盖了的基类方法,而不用声明 是哪个类定义了该方
    法。(注:不要把这个和第十一章的覆盖 Perl 的内建函数的机制混淆 了,那个不是对象方法并且不会被继承覆
    盖。你调用内建函数的覆盖是通过 CORE 伪包,而 不是 SUPER 伪包。)下面的子过程在当前包的 @ISA 里查
    找,而不会要求你声明特定类:
    
    
    [root@wx03 test]# cat Horse.pm 
    
    当前类:
    
    package Horse;
    our @ISA = "Critter";
    sub new {
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
    my $self = {
    color => "bay",
    legs => 4,
    owner => undef,
    @_, # 覆盖以前的属性
    };
    return bless $self, $class;
    };
    sub sum1 {
           $self=shift;
           my $a=shift;
           my $b=shift;
           return $a + $b + 7;
    };
    1;
    
    
    [root@wx03 test]# cat Critter.pm 
    
    基类:
    
    package Critter;
    sub new {
        my $self = {};
        my $invocant = shift;    
    my $class = ref($invocant) || $invocant;
    	my ($name)=@_;    
          my $self = {    
             "name" =>$name    
                     };  
        bless $self, $class; # Use class name to bless() reference
        return $self;
    
    };
    
    sub sum1 {
           $self=shift;
           my $a=shift;
           my $b=shift;
           return $a + $b;
    };
    
    
    sub fun1 {
           $self=shift;
           my $a=shift;
           my $b=shift;
           return $a / $b;
    }
    1;
    
    
    [root@wx03 test]# cat t6.pl 
    unshift(@INC,"/root/test"); 
    use Horse;;
    use base qw(Critter);
    require Critter;
    use Data::Dumper;
    $ed = Horse->new; # 四腿湾马
    print $ed->sum1(4,5);
    print "
    ";
    print $ed->sum1(4,5);
    print "
    ";
    
    [root@wx03 test]# perl t6.pl 
    16
    16
    
    
    此时由于当前包的方法覆盖了基类的方法 所以都是16
    
    
    
    
    [root@wx03 test]# cat t6.pl 
    unshift(@INC,"/root/test"); 
    use Horse;;
    use base qw(Critter);
    require Critter;
    use Data::Dumper;
    $ed = Horse->new; # 四腿湾马
    print $ed->sum1(4,5);
    print "
    ";
    print $ed->SUPER::sum1(4,5);
    print "
    ";
    [root@wx03 test]# perl t6.pl 
    16
    9
    
    这时候会访问覆盖的方法

  • 相关阅读:
    .hpp文件
    最小高度的BST
    检查图中的有向路径
    c++ 对象内存布局详解
    链表求差
    offer--链表反转和从尾到头打印链表
    平衡二叉树的判断
    java 抽象类和接口
    原型模式--prototype
    装饰模式decorator
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13350783.html
Copyright © 2020-2023  润新知