脚本宝典收集整理的这篇文章主要介绍了rudy 重载方法 详解,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
在子类里,我们可以通过重载父类方法来
改变实体的行为.
r
uby>&nbs
p;class Human
| def identify
|
PRint "I'm a
PErson.\n"
| end
| def tr
ain_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 Student1<Human
| def identify
| print "I'm a student.\n"
| end
| end
nil
ruby> Student1.new.identify
I'm a student.
nil
如果我们只是想增强父类的 identify 方法而不是完全地替代它,就可以用 super.
ruby> class Student2<Human
| 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 Dishonest<Human
| 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 Honest<Human
| 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 重载方法 详解所遇到的问题。
如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。