python——动态的增加实例方法、类方法、静态方法
生活随笔
收集整理的這篇文章主要介紹了
python——动态的增加实例方法、类方法、静态方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
初始類為:
import typesclass Person:def __init__(self,name,age):self.name=nameself.age=ageif __name__ == '__main__':p=Person('kb',18)1、動態增加一個類屬性
Person.sex='女'2、類不能調用實例對象
print(Person.age)報錯:
AttributeError: type object ‘Person’ has no attribute ‘age’
3、對象調用類屬性
print(p.sex)4、動態增加實例方法
def run(self,work):print(f'實例方法:{self.name}正在{work}')p.run=types.MethodType(run,p)p.run('學習')5、給Person類增加一個類方法
@classmethoddef class_run(cls,work):print(f'類方法:正在{work}')Person.class_run=class_runp.class_run('學習')6、給Person類增加一個靜態方法
@staticmethoddef static_run(work):print(f'靜態方法:正在{work}')Person.static_run=static_runp.static_run('學習')總結
以上是生活随笔為你收集整理的python——动态的增加实例方法、类方法、静态方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: git之常用命令二
- 下一篇: websocket python爬虫_p