Python面向对象之 - 继承
情况一: 子类完全继承父类所有的属性和方法, 自己没有一点更改.
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print("跑步!")
def eat(self, food):
print("吃%s!"%food)
class Student(Person):
pass # 用pass占位, 完全继承父类的一切, 而且不做任何修改.
stu = Student("tom", 18)
print(stu.name, stu.age)
stu.run()
stu.eat("apple")<br /><br /># 结果:<br /># tom 18<br /># 跑步!<br /># 吃apple!情况二: 子类继承父类的所有属性和方法, 而且自己想要增加新的方法.
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print("跑步!")
def eat(self, food):
print("吃%s!"%food)
class Student(Person):
def drink(self): # 增加父类中没有的新的方法.<br /> print("喝水!")
stu = Student("tom", 18)
print(stu.name, stu.age)
stu.run()
stu.eat("apple")<br />stu.drink()
# 结果:
# tom 18
# 跑步!
# 吃apple!<br /># 喝水!情况三:子类继承自父类, 但是自己想要完全替换掉父类中的某个方法.
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print("跑步!")
def eat(self, food):
print("吃%!"%food)
class Student(Person):
def eat(self): # 重写父类方法, 将会完全覆盖掉原来的父类方法.<br /> print("吃东西!")<br />
stu = Student("tom", 18)
print(stu.name, stu.age)
stu.run()
stu.eat()
# 结果:
# tom 18
# 跑步!
# 吃东西!情况四:子类继承父类的所有属性和方法, 并且想在原有父类的属性和方法的基础上做扩展.
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print("跑步!")
def eat(self, food):
print("吃%s!"%food)
class Student(Person):
def __init__(self, name, age, height):
super(Student, self).__init__(name, age) # 对父类属性进行扩展
self.height = height # super()内的(子类名, self)参数可以不写
def eat(self, food):
super(Student, self).eat(food) # 对父类方法进行扩展
print("再吃一个!") # super()内的(子类名, self)参数可以不写
stu = Student("tom", 18, 175)
print(stu.name, stu.age, stu.height)
stu.run()
stu.eat("apple")<span># 结果:<br /># tom 18 175<br /># 跑步!<br /># 吃apple!<br /># 再吃一个!
相关推荐
weiiron 2020-08-17
joyjoy0 2020-08-13
qiximiao 2020-08-03
huakai 2020-07-26
生物信息学 2020-06-22
荒乱的没日没夜 2020-06-14
adamlovejw 2020-06-11
RocNg 2020-06-01
Keepgoing 2020-05-26
lqxqust 2020-05-19
class Singleton: def __new__: # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象 if not hasattr: cls.instance =
lhxxhl 2020-05-16
HongKongPython 2020-05-12
wangqing 2020-05-10
Lexan 2020-05-09
cenylon 2020-05-08
宿舍 2020-05-06