1. 程式人生 > >python學習日記(OOP資料封裝)

python學習日記(OOP資料封裝)

class Student(object):
    def __init__(self,name,score):
        self.name = name
        self.score = score
li = Student('libai','99')
print(li.name)
print(li.score)

面向物件程式設計的一個重要特點就是資料封裝。在上面的Student類中,每個例項就擁有各自的namescore這些資料。我們可以通過函式來訪問這些資料,比如列印一個學生的成績:

def print_score(student):
    
print('{}的成績是:{}'.format(student.name,student.score)) print_score(li)

但是,既然Student例項本身就擁有這些資料,要訪問這些資料,就沒有必要從外面的函式去訪問,可以直接在Student類的內部定義訪問資料的函式,這樣,就把“資料”給封裝起來了。這些封裝資料的函式是和Student類本身是關聯起來的,我們稱之為類的方法:

class Student(object):
    def __init__(self,name,score):
        self.name = name
        self.score 
= score def print_score(self): print('{}的成績是:{}'.format(self.name, self.score))

要定義一個方法,除了第一個引數是self外,其他和普通函式一樣。要呼叫一個方法,只需要在例項變數上直接呼叫,除了self不用傳遞,其他引數正常傳入:

li.print_score()

這樣一來,我們從外部看Student類,就只需要知道,建立例項需要給出namescore,而如何列印,都是在Student類的內部定義的,這些資料和邏輯被“封裝”起來了,呼叫很容易,但卻不用知道內部實現的細節。

封裝的另一個好處是可以給Student類增加新的方法,比如get_grade

class Student(object):
    def __init__(self,name,score):
        self.name = name
        self.score = score
    def print_score(self):
        print('{}的成績是:{}'.format(self.name, self.score))
    
    def get_grade(self):
        if self.score >= 90:
            return 'A'
        elif self.score >=60:
            return 'B'
        else:
            return 'C'

同樣的,get_grade方法可以直接在例項變數上呼叫,不需要知道內部實現細節:

class Student(object):
    def __init__(self,name,score):
        self.name = name
        self.score = score
    def print_score(self):
        print('{}的成績是:{}'.format(self.name, self.score))

    def get_grade(self):
        if self.score >= 90:
            return 'A'
        elif self.score >= 60:
            return 'B'
        else:
            return 'C'
wang = Student('WangDong',92)
liang = Student('LiangMeng',46)
print(wang.name,wang.get_grade())
print(liang.name,liang.get_grade())

小結:

類是建立例項的模板,而例項則是一個一個具體的物件,各個例項擁有的資料都互相獨立,互不影響;

方法就是與例項繫結的函式,和普通函式不同,方法可以直接訪問例項的資料;

通過在例項上呼叫方法,我們就直接操作了物件內部的資料,但無需知道方法內部的實現細節。

和靜態語言不同,Python允許對例項變數繫結任何資料,也就是說,對於兩個例項變數,雖然它們都是同一個類的不同例項,但擁有的變數名稱都可能不同:

>>> bart = Student('Bart Simpson', 59)
>>> lisa = Student('Lisa Simpson', 87)
>>> bart.age = 8
>>> bart.age
8
>>> lisa.age
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'age'

參考原始碼

 student.py