面向對象--02面向對象的三個基本特徵

1.面向對象的三大特徵 之 封裝
通常把隱藏 屬性、方法與方法實現細節 的過程 稱爲封裝

爲了保護類裏面的屬性,避免外界隨意賦值,可以採用以下方法解決:
①把屬性定義爲私有屬性,即屬性名前加兩個下劃線

②添加可以供外界調用的兩個方法,分別用於設置或者獲取屬性值

class Person:
    def __init__(self,name,age):
        self.name = name
        self.__age = age
    #給私有屬性賦值
    def setnemage(self,newage):
        if newage > 0 and newage <= 120:
            self.__age = newage
    #獲取私有屬性
    def getage(self):
        return self.__age
>>> laowang = Person('老王',30)
>>> laowang.name
'老王'
>>> laowang.__age
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    laowang.__age
AttributeError: 'Person' object has no attribute '__age'
>>> laowang.getage()
30
>>>


2.面向對象的三大特徵 之 繼承

父類的私有屬性和私有方法是不會被子類繼承的,更不能被子類訪問。

注意:當一個類的內部定義了私有方法或者私有屬性的時候,Python在運行的過程中,把屬性或者方法的名字(不帶兩個下劃線)進行了修改,即在屬性或者方法名稱的前面加上'_類名',導致原有的方法和屬性無法被訪問到。

語法:
class 子類(父類1,父類2,····)


①重寫父類的方法

例:

#定義表示人的類
class Person(object):
    #打招呼的方式
    def sayhello(self):
        print('--hello--')

#定義Chinese類繼承自Person類
class Chinese(Person):
    #中國人打招呼的方式
    def sayhello(self):
        print('吃了嗎')

#創建Chinese類的對象
chinese = Chinese()
chinese.sayhello()

#創建另一個實例
eng = Person()
eng.sayhello()
>>> 吃了嗎
>>> --hello--


2.1
如果子類想要調用父類中被重寫的方法,需要使用super方法訪問父類中的成員。
super() 函數用於調用下一個父類(超類)並返回該父類實例的方法。

語法:
super(cls[, object-or-cls])

cls                -->          類

object-or-cls       -->   一般是 self

例:

class FooParent(object):
    def __init__(self):
        self.parent = 'I\'m the parent.'
        print ('Parent')
    
    def bar(self,message):
        print ("%s from Parent" % message)

        
class FooChild(FooParent):
    def __init__(self):
        # super(FooChild,self) 首先找到 FooChild 的父類(就是類 FooParent),然後把類B的對象 FooChild 轉換爲類 FooParent 的對象
        super(FooChild,self).__init__()    
        print ('Child')
        
    def bar(self,message):
        super(FooChild, self).bar(message)
        print ('Child bar fuction')
        print (self.parent)
>>> fooChild = FooChild()
Parent
Child
>>> fooChild.bar('HelloWorld')
HelloWorld from Parent
Child bar fuction
I'm the parent.
>>>


例:

#定義父類Animal
class Animal(object):
    def __init__(self,legnum):
        #腿的數量
        self.legnum = legnum

#定義Bird類繼承自Animal
class Bird(Animal):
    #重寫了父類的init方法
    def __init__(self,legnum):
        #增加特有的屬性
        self.plume = '白色'
        #調用父類的init方法
        super().__init__(legnum)

bird = Bird(2)
print('有一隻%s條腿%s羽毛的鳥兒在樹上唱歌'%(bird.legnum,bird.plume))

>>>有一隻2條腿白色羽毛的鳥兒在樹上唱歌


2.2
當使用繼承不合適時,可用組合

class Turtle:
    def __init__(self,x):
        self.num = x

class Fish:
    def __init__(self,x):
        self.num = x

class Pool:
    def __init__(self,x,y):
        self.turtle = Turtle(x)
        self.fish = Fish(y)
>>> pool=Pool(1,2)
>>> pool.turtle.num
1
>>>


所謂組合就是把類的實例化放到一個新類裏面,組合用於橫向 沒有繼承關係的類放在一起。


3.面向對象的三大特徵 之 多態
調用同一個方法,出現了兩種表現形式,這個過程體現的就是多態

在Python中,多態指在不考慮對象類型的情況下使用對象。Python更推崇‘鴨子類型’。也就是想說,它不關注對象的類型,而是關注對象的具體行爲。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章