Python 學習小結

來源:互聯網
上載者:User

標籤:student   strong   多態   instance   error   ack   python   bsp   nbsp   

假期閑來無事,撿起Python再看一遍,略有收穫,記載如下。

 

首先,Python中有function和method的區別,從types.MethodType和types.FunctionType就可以看出,其區別在於method是Class中的函數,但只能叫方法;此外的函數都是function。

其次,Python是動態語言,也就是鴨子類型:只要看起來像鴨子,舉止行為像鴨子,那就認為這是鴨子。這就是Python的多態,與Java明顯不同。

 

Python也有Class和instance的區別:前者是抽象,後者是執行個體。

與Java不同的是,Python支援動態添加屬性(值或者方法/函數,值沒有好說的,這裡我們只討論函數/方法):可以給instance添加屬性(僅用於當前對象),也可以給Class添加屬性(可用於所有對象)!

以Class Student為例:

class Student(object):    pass

給Student類本身添加方法很簡單,只需要定義一個方法,然後將其賦予Student的屬性即可!唯一需要記住的是,方法的第一個參數必須是self。如下:

def set_age(self, age):    self.age = ageStudent.set_age = set_age  # 這樣即可!stu = Student()stu.set_age(18)print(stu.age) # 這裡會得到18

而給Student的instance添加屬性方法則比較麻煩,需要將定義的函數轉成MethodType,再賦予Student的instance的屬性。同樣的,方法的第一個參數必須是self。如下:

import typesdef set_name(self, name):    self.name = namestu = Student()# stu.set_name = set_name # DONTstu.set_name = types.MethodType(set_name, stu) # 必須這樣stu.set_name(‘LarryZeal‘)print(stu.name)

至於必須轉成MethodType的原因,可以通過執行上面被注釋掉的代碼來說明:

import typesdef set_name(self, name):    self.name = namestu = Student()stu.set_name = set_name # DONTstu.set_name(‘LarryZeal‘) # ERROR! 不知道self是什麼print(stu.name)

就是說,直接調用的是function,而非method。個人認為,二者的區別在於self:Class會主動將對象綁定到self,其他的不會!

 

按照這個推測,其實可以輸出下上面兩種情況的屬性的type:

print(type(stu.set_name))

一種是method,一種是function!

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.