主页 > 知识库 > rudy 重载方法 详解

rudy 重载方法 详解

热门标签:征服者企业地图标注 漯河电销 中牟外呼系统违法吗 淮安自动外呼系统供应商 柯城手机地图如何做地图标注 巫师3地图标注魔力之所 天津外呼系统怎么收费 外呼线路从哪里出来的 AI电销机器人 线路
在子类里,我们可以通过重载父类方法来改变实体的行为.

ruby> class Human
    |   def identify
    |     print "I'm a person.\n"
    |   end
    |   def train_toll(age)
    |     if age  12
    |       print "Reduced fare.\n";
    |     else
    |       print "Normal fare.\n";
    |     end
    |   end
    | end
   nil
ruby> Human.new.identify
I'm a person.
   nil
ruby> class Student1Human
    |   def identify
    |     print "I'm a student.\n"
    |   end
    | end
   nil
ruby> Student1.new.identify
I'm a student.
   nil  


如果我们只是想增强父类的 identify 方法而不是完全地替代它,就可以用 super.

ruby> class Student2Human
    |   def identify
    |     super
    |     print "I'm a student too.\n"
    |   end
    | end
   nil
ruby> Student2.new.identify
I'm a human.
I'm a student too.
   nil  


super 也可以让我们向原有的方法传递参数.这里有时会有两种类型的人...

ruby> class DishonestHuman
    |   def train_toll(age)
    |     super(11) # we want a cheap fare.
    |   end
    | end
   nil
ruby> Dishonest.new.train_toll(25)
Reduced fare. 
   nil

ruby> class HonestHuman
    |   def train_toll(age)
    |     super(age) # pass the argument we were given
    |   end
    | end
   nil
ruby> Honest.new.train_toll(25)
Normal fare. 
   nil   

标签:大庆 河池 克拉玛依 内江 枣庄 西双版纳 南昌 甘孜

巨人网络通讯声明:本文标题《rudy 重载方法 详解》,本文关键词  rudy,重载,方法,详解,rudy,;如发现本文内容存在版权问题,烦请提供相关信息告之我们,我们将及时沟通与处理。本站内容系统采集于网络,涉及言论、版权与本站无关。
  • 相关文章
  • 下面列出与本文章《rudy 重载方法 详解》相关的同类信息!
  • 本页收集关于rudy 重载方法 详解的相关信息资讯供网民参考!
  • 推荐文章