Python面向對象之 - 繼承

狀況一:  子類徹底繼承父類全部的屬性和方法, 本身沒有一點更改.app

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")

# 結果:
# tom 18
# 跑步!
# 吃apple!

 

狀況二:  子類繼承父類的全部屬性和方法,  並且本身想要增長新的方法.spa

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):           # 增長父類中沒有的新的方法.
     print("喝水!")
stu = Student("tom", 18) print(stu.name, stu.age) stu.run() stu.eat("apple")
stu.drink()
# 結果: # tom 18 # 跑步! # 吃apple!
# 喝水!

 

狀況三:  子類繼承自父類,  可是本身想要徹底替換掉父類中的某個方法.code

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):           # 重寫父類方法, 將會徹底覆蓋掉原來的父類方法.
     print("吃東西!")
stu = Student("tom", 18) print(stu.name, stu.age) stu.run() stu.eat() # 結果: # tom 18 # 跑步! # 吃東西!

 

狀況四:  子類繼承父類的全部屬性和方法,  而且想在原有父類的屬性和方法的基礎上作擴展.blog

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")
# 結果:# tom  18  175# 跑步!# 吃apple!# 再吃一個!
相關文章
相關標籤/搜索