python學習日記-物件導向編程(一)

來源:互聯網
上載者:User

標籤:...   nbsp   編程   ret   size   com   self   對象   www   

python的類(class)和執行個體(instance)

  假設一種鞋子(shoe)有尺碼(size)和顏色(color)兩種屬性,以此為例。

  類可以起到模板的作用,因此,可以在建立執行個體的時候,把一些我們認為必須綁定的屬性強制填寫進去。通過定義一個特殊的__init__方法,在建立執行個體的時候,就把size,color屬性綁到shoe上去,例如:

       

1 class Shoe(object):2 3     def __int__(self, size, color):4         self.size = size5         self.color = color

  其中,(object)表示繼承自哪個類,如果沒有合適的繼承類,就用object;

  self表示執行個體本身,所以使用__int__方法添加屬性,可以把屬性添加到self;

 

資料的封裝

  從類的內部定義訪問資料的函數,這樣就可以把資料封裝起來。例如:

1 class Shoe(object):2 3     def __init__(self, size, color):4         self.size = size5         self.color = color6 7     def get_color(self):8         print(‘%s: %s‘ % (self.size, self.color))

  要定義一個方法,除了第一個參數是self外,其他和普通函數一樣。

  要調用一個方法,只需要在執行個體變數上直接調用,除了self不用傳遞,其他參數正常傳入:

>>> bart.get_color()32: black

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

 1 class Shoe(object): 2     ... 3  4     def get_level(self): 5         if self.size >= 40: 6             return ‘A‘ 7         elif self.size >= 32: 8             return ‘B‘ 9         else:10             return ‘C‘

  可以簡單的調用get_level,例如:

>>>46.get_level()‘A‘

註:參考廖雪峰老師的網站http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431864715651c99511036d884cf1b399e65ae0d27f7e000

python學習日記-物件導向編程(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.