欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python面向?qū)ο笾惖姆庋b操作示例

 更新時間:2019年06月08日 10:13:41   作者:feesland  
這篇文章主要介紹了Python面向?qū)ο笾惖姆庋b操作,結(jié)合具體實(shí)例形式分析了Python面向?qū)ο蟪绦蛟O(shè)計(jì)中類方法的定義與使用相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Python面向?qū)ο笾惖姆庋b操作。分享給大家供大家參考,具體如下:

承接上一節(jié)《Python面向?qū)ο笾惡蛯?shí)例》,學(xué)了Student類的定義及實(shí)例化,每個實(shí)例都擁有各自的name和score?,F(xiàn)在若需要打印一個學(xué)生的成績,可定義函數(shù) print_score()

該函數(shù)為類外的函數(shù),如下:

class Student(object):
  def __init__(self, name, score):
    self.name = name
    self.score = score
May = Student("May",90)           # 須要提供兩個屬性
Peter = Student("Peter",85)
print(May.name, May.score)
print(Peter.name, Peter.score)
def print_score(Student):          # 外部函數(shù)print_score(Student)
  # print("%s's score is: %d" %(Student.name,Student.score))       # 普通 print 寫法
  print("{0}'s score is: {1}".format(Student.name,Student.score))    # 建議使用 Python 2.7 + .format優(yōu)化寫法
print_score(May)
print_score(Peter)

既然Student實(shí)例本身就擁有這些數(shù)據(jù),要訪問這些數(shù)據(jù),就沒有必要從外面的函數(shù)去訪問,我們可以直接在Student類的內(nèi)部定義訪問數(shù)據(jù)的函數(shù)。這樣,就把數(shù)據(jù)給“封裝”起來了。

“封裝”就是將抽象得到的數(shù)據(jù)和行為(或功能)相結(jié)合,形成一個有機(jī)的整體(即類);封裝的目的是增強(qiáng)安全性和簡化編程,使用者不必了解具體的實(shí)現(xiàn)細(xì)節(jié),而只是要通過外部接口,一特定的訪問權(quán)限來使用類的成員。

而這些封裝數(shù)據(jù)的函數(shù)是和Student類本身是關(guān)聯(lián)起來的,我們稱之為類的方法。那如何定義類的方法呢?

就要用到對象 self 本身,參考上例,把 print_score() 函數(shù)寫為類的方法(Python2.7之后的版本,推薦.format 輸出寫法):

class Student(object):
  def __init__(self, name, score):
    self.name = name
    self.score = score
  def print_score(self):
    print("{self.name}'s score is: {self.score}".format(self=self))    # Python 2.7 + .format優(yōu)化寫法
May = Student("May",90)
Peter = Student("Peter",85)

定義類的方法:除了第一個參數(shù)是self外,其他和普通函數(shù)一樣。

實(shí)例調(diào)用方法:只需要在實(shí)例變量上直接調(diào)用,除了self不用傳遞,其他參數(shù)正常傳入;注意,若類的方法僅需要self,不需要其他,調(diào)用該方法時,僅需 instance_name.function_name()

這樣一來,我們從外部看Student類,就只需要知道,創(chuàng)建實(shí)例需要給出name和score,而如何打印,都是在Student類的內(nèi)部定義的,這些數(shù)據(jù)和邏輯被“封裝”起來了,調(diào)用很容易,但卻不用知道內(nèi)部實(shí)現(xiàn)的細(xì)節(jié)。

封裝的另一個好處是可以給Student類增加新的方法;這邊的方法也可以要求傳參,如新增定義compare 函數(shù),如下:

class Student(object):
  def __init__(self, name, score):
    self.name = name
    self.score = score
  def print_score(self):
    print("{self.name}'s score is: {self.score}".format(self=self))    # Python 2.7 + .format優(yōu)化寫法
  def compare(self,s):
    if self.score>s:
      print("better than %d" %(s))
    elif self.score==s:
      print("equal %d" %(s))
    else:
      print("lower than %d" %(s))
May = Student("May",90)
Peter = Student("Peter",85)
May.print_score()
Peter.print_score()
May.compare(100)
May.compare(90)
May.compare(89)

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O(shè)計(jì)入門與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程

希望本文所述對大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論