python 動(dòng)態(tài)添加實(shí)例方法和類方法

通過 types 模塊動(dòng)態(tài)添加實(shí)例方法和類方法的實(shí)踐筆記

import types


class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def speak_age(self):
        print(f"age is {self.age}")


def speak_name(self):
    print(f"name is {self.name}")


@staticmethod
def add_static_method():
    print("call add_static_method")


@classmethod
def add_class_method(cls):
    print("call add_class_method")


if __name__ == "__main__":
    tom = Person("tom", 30)
    tom.speak_age()
    # 添加實(shí)例方法,并調(diào)用
    tom.speak_name = types.MethodType(speak_name, tom)
    tom.speak_name()

    # 添加靜態(tài)方法
    Person.add_static_method = add_static_method
    # 添加類方法
    Person.add_class_method = add_class_method
    tom.add_static_method()
    tom.add_class_method()
    # 新實(shí)例依然可以調(diào)用
    ana = Person("ana", 18)
    ana.add_static_method()

運(yùn)行后控制臺(tái)輸出


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容