本文實例講述了Python實現動態添加屬性和方法操作。分享給大家供大家參考,具體如下:
# -*- coding:utf-8 -*-#!python3class Person(): def __init__(self, name, age): self.name = name self.age = agep1 = Person('ff', '28')print(p1.name, p1.age)# 給實例對象動態添加sex屬性p1.sex = 'female'print(p1.sex)# 給類動態添加屬性Person.height = Noneprint(Person.height)p1.height = '155'print(p1.height)# 動態定義一個方法def run(self, speed): print('run with %d speed' % speed)# 給實例綁定方法import typesp1.run = types.MethodType(run, p1)p1.run(30)# Person.run = run # 運行錯誤 # Person.run(4)@classmethoddef run2(a, speed): print('run with %d m/s' % speed)# 給類動態綁定方法Person.run2 = run2 # 給類綁定的方法, 需加修飾器 @classmethod, 標定其為類方法,可被類添加Person.run2(4)p1.run2(5) # 類的實例對象也可調用類動態添加的方法@staticmethoddef eat(): print('eat---')Person.eat = eat # 類可添加靜態方法, 定義靜態方法時,需加修飾器@staticmethodPerson.eat()p1.eat() # 實例對象同樣可調用類動態添加的靜態方法del p1.name # del 刪除屬性delattr(p1, 'sex')print(p1.name, p1.sex)
運行結果:
ff 28
female
None
155
run with 30 speed
run with 4 m/s
run with 5 m/s
eat---
eat---
Traceback (most recent call last):
File "/home/python/Desktop/test/12_動態語言.py", line 41, in <module>
print(p1.name, p1.sex)
AttributeError: 'Person' object has no attribute 'name'
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python面向對象程序設計入門與進階教程》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答