[Python3] 類的高級用法:給實例和類動態綁定屬性和方法

Python是動態語言,它可以在寫好了一個類之後再給類動態地添加屬性和方法
對於類生成出的實例同樣可以這樣做


要實現這一功能需要藉助一個方法:MethodType

用法:

<類(或者實例)>.<爲要添加的方法或屬性起的名字> = MethodType(<要添加的方法或屬性>, 類(或者實例))


舉例:

可以先這樣導入這個方法 from types import MethodType
假設我們定義一個 Student 類:

class Student(object):
    pass

現在裏面什麼也不寫,我們在外面給它動態增加方法
考慮這樣一個函數:

def set_score(self, score: int):
    self.score = score

只需寫入這樣一行代碼即可把set_score() 方法添加爲 Student 類的 .set_score() 方法:

Student.set_score = MethodType(set_score, Student)

之後就可以這樣使用這個方法了:

Student.set_score(99)

綁定屬性以及對類實例綁定的做法類似

下面是一個DEMO:

# 類的高級用法1

from types import MethodType


class Student(object):
    pass


def main():
    s = Student()
    s.name = 'Bob'
    print(s.name)

    def set_age(self, age: int):    # 給實例定義的方法
        self.age = age

    s.set_age = MethodType(set_age, s)  # 將方法與一個實例綁定, 這樣實例s就有了set_age()方法

    s.set_age(5)                        # 這樣一來實例s有了一個屬性: s = 5
    print(s.age)

    # 當然也可以給類綁定方法
    def set_score(self, score: int):
        self.score = score

    Student.set_score = MethodType(set_score, Student)
    Student.set_score(99)
    print(Student.score)
    # 這樣Student類就有了set_score()方法和score屬性,該類所有實例都可用,如下:

    s.set_score(80)
    print(s.score)  # 會輸出80而不是99


if __name__ == '__main__':
    main()

運行結果:

Bob
5
99
80
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章