Python中的繼承
阿新 • • 發佈:2018-11-13
ass Cat(object): # def __init__(self, name = '動物',color = "白色"): # self.name = name # self.color = color # def test(self): # print(self.__name) # print(self.color) # # def run(self): # # print("%s————在跑步"%self.name) # class bosi(Cat): # def setNewName(self,newName): # self.name = newName # def eat(self): # print("%s__在吃"%self.name) # # b = bosi("印度貓") # print('b的名字是:%s'%b.name) # print("b的顏色是%s"%b.color) # b.eat() # b.setNewName('波斯') # b.run() class Animal(object): def __init__(self, name = '動物',color = "白色"): self.name = name self.color = color def test(self): print(self.__name) print(self.color) # def run(self): # print("%s————在跑步"%self.name) class Dog(Animal): def dogTest1(self): print(self.__name) def dogTest2(self): self._test() # A = Animal() # # print(A.__name) # A.test() print("分割線") D = Dog(name = "小花狗",color = "黃色") D.dogTest1() D.dogTest2()
說明:
雖然子類沒有定義__init__方法,但是父類有,所以在子類繼承父類的時候這個方法就被繼承了,所以只要建立Bosi的物件,就預設執行了那個繼承過來的__init__方法
總結
1、子類在繼承的時候,在定義類時,小括號()中為父類的名字
2、父類的屬性、方法,會被繼承給子類
1、私有的屬性,不能通過物件直接訪問,但是可以通過方法訪問
2、私有的方法,不能通過物件直接訪問
3、私有的屬性、方法,不會被子類繼承,也不能被訪問
4、一般情況下,私有的屬性、方法都是不對外公佈的,往往用來做內部的事情,起到安全的作用