Python - 繼承(Inheritance) 詳解 及 代碼

http://blog.csdn.net/caroline_wendy/article/details/20357767


繼承可以使代碼重用, 是類型和子類型的關係;

Python中, 繼承是在類名的括號中填入繼承的基類, 即class DerivedClass(BaseClass):

基類初始化需要使用self變量, 即BaseClass.__init__(self, val1, val2), 需要手動調用基類的構造函數;

派生共享基類的成員變量, 可以直接使用self.val進行使用;

可以重寫(override)基類的方法, 則使用時, 會優先調用派生類的方法;


代碼如下:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print('(Initialized Person: {0})'.format(self.name))
        
    def tell(self):
        print('Name:"{0}" Age:"{1}"'.format(self.name, self.age))
        
class Man(Person): #繼承
    def __init__(self, name, age, salary):
        Person.__init__(self, name, age)
        self.salary = salary
        print('(Initialized Man: {0})'.format(self.name))
        
    def tell(self): #重寫基類方法
        Person.tell(self)
        print('Salary: "{0:d}"'.format(self.salary))
        
class Woman (Person):
    def __init__(self, name, age, score):
        Person.__init__(self, name, age)
        self.score = score
        print('(Initialized Woman: {0})'.format(self.name))
        
    def tell(self): #重寫基類方法
        Person.tell(self)
        print('score: "{0:d}"'.format(self.score))
            
c = Woman('Caroline', 30, 80)
s = Man('Spike', 25, 15000)
print('\n')
members = [c, s]
for m in members:
    m.tell()

輸出:

(Initialized Person: Caroline)
(Initialized Woman: Caroline)
(Initialized Person: Spike)
(Initialized Man: Spike)


Name:"Caroline" Age:"30"
score: "80"
Name:"Spike" Age:"25"
Salary: "15000"


發佈了20 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章