標籤: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 學習小結