詳解Python類與對象(下)

前言

上節課我們介紹了Python面向對象的基本概念和使用,本節課將繼續講解Python面向對象,主要分爲兩個部分,第一個是繼承,第二個是私有化。

希望這兩次分享能讓初學者能夠基本瞭解Python面向對象編程,並按實際需求編寫出自己定義的類。

繼承

繼承是每個人的夢想。

繼承的寫法很簡單,只需要在定義子類時,指定父類即可。

class Animal:

    leg = 4

    def __init__(self, species, furcolor):
        self.species = species
        self.furcolor = furcolor

    def call(self):
        return '{} is calling'.format(self.species)


class Dog(Animal):

    def __init__(self, species, furcolor, name):
        super().__init__(species, furcolor)
        self.name = name

    def get_name(self):
        print(self.name)


dog1 = Dog('dog', 'red', 'lucky')
print(dog1.call())
print(dog1.leg)
dog1.get_name()

dog is calling
4
lucky

繼承其實比較好理解的,子類可以調用父類的屬性和方法,如果子類重新進行了定義(我們通常叫重寫),那就會使用子類的屬性。

論私有化

在正式聊私有化之前,我希望你記住一句話,Python的私有化不是真正意義上的私有化。

默認情況下,我們是可以直接發問對象的屬性和方法的,如下所示。

class Animal:

    leg = 4

    def __init__(self, species, furcolor):
        self.species = species
        self.furcolor = furcolor

    def call(self):
        return '{} is calling'.format(self.species)


dog = Animal('dog', 'gray')
print(dog.species)

dog

但有人覺得這樣做破壞了封裝的原則,我認爲主要原因有兩個。

第一目的是爲了讓程序員直接調用接口(可能是部分方法),而不用去關心具體內容,因爲對他們而言,調用這些屬性和方法沒有意義。

第二個目的是在繼承時的考慮,如果子類和父類具有同樣的屬性,那子類必定會覆蓋屬性,,定義了私有屬性可以防止這樣的事情發生。

那怎麼讓屬性私有化了?其實很簡單,我們用雙下劃線開始定義屬性即可。

class Animal:

    leg = 4

    def __init__(self, species, furcolor):
        self.__species = species
        self.furcolor = furcolor

    def call(self):
        return '{} is calling'.format(self.species)


dog = Animal('dog', 'gray')
print(dog.species)

Traceback (most recent call last):
  File "/Users/luopan/Python練習/Python基礎語法/類與對象.py", line 136, in <module>
    print(dog.species)
AttributeError: 'Animal' object has no attribute 'species'

還記得我之前說的那句話嗎,真的不能調用了嗎?我們來看看實例的dict屬性。

class Animal:

    leg = 4

    def __init__(self, species, furcolor):
        self.__species = species
        self.furcolor = furcolor

    def call(self):
        return '{} is calling'.format(self.species)


dog = Animal('dog', 'gray')
print(dog.__dict__)

{'_Animal__species': 'dog', 'furcolor': 'gray'}

我們發現其實私有屬性改爲了_Animal__species,所以調用它,也是可以反問私有屬性的。

dog = Animal('dog', 'gray')
print(dog._Animal__species)

dog

所以,有人不太贊同這種寫法,並使用單下劃線來代替,易於理解,定下這個規定,程序員也不在類外部訪問這種屬性。

總結

今天的分享就到這了,但Python類與對象的並不止這些,接下來我會慢慢分享給大家,希望大家持續關注羅羅攀,我們下期再見~

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