在子类里,我们可以通过重载父类方法来改变实体的行为.
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 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
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
-
循序渐进掌握递归正则表达式
一般来说,递归的正则表达式用来匹配任意嵌套层次的结构或左右对称的结构。例如匹配: 递归正则在正则表达式里算是比较灵活的部分,换句话说就是可能会比较难...
[阅读全文]
-
scrapy 使用
启动方式: 写一个启动文件,与配置文件同级 from scrapy.cmdline import execute import sys,os sys...
[阅读全文]
-
-
-
经典例题
例题: 1.用户输入账号 2.用户输入密码 3.判断用户的账号是不是alex 4.如果账号是alex在继续判断密码是不是alexdsb 5.账号和密...
[阅读全文]
-
-
-
-
-
网友评论