给Python的类和对象动态增加属性和方法
通常我們會(huì)將編程語(yǔ)言分為靜態(tài)和動(dòng)態(tài)。靜態(tài)語(yǔ)言的變量是在內(nèi)存中的有類(lèi)型的且不可變化的,除非強(qiáng)制轉(zhuǎn)換它的類(lèi)型;動(dòng)態(tài)語(yǔ)言的變量是指向內(nèi)存中的標(biāo)簽或者名稱(chēng),其類(lèi)型在代碼運(yùn)行過(guò)程中會(huì)根據(jù)實(shí)際的值而定。Python就是典型的動(dòng)態(tài)語(yǔ)言。
1.動(dòng)態(tài)添加屬性
當(dāng)類(lèi)或者對(duì)象的屬性在需要增加的時(shí)候,對(duì)于不方便修改源碼的情況下,我們可以選擇動(dòng)態(tài)的對(duì)其添加屬性。
(1 動(dòng)態(tài)給對(duì)象添加屬性
對(duì)象屬性只在當(dāng)前對(duì)象生效,在其他對(duì)象中是無(wú)法調(diào)用的。
定義一個(gè)類(lèi):
class Student(object):def __init__(self,name,age):self.name=nameself.age=age執(zhí)行:(給實(shí)例添加數(shù)學(xué)成績(jī)屬性并且初始化)
>>> from payhlib import Student >>> s=Student('xiaoming',18) >>> s.name 'xiaoming' >>> s.age 18 >>> s.math_score=100 >>> s.math_score 100 >>> ss=Student('laowang',28) >>> ss.name 'laowang' >>> ss.age 28 >>> ss.math_score Traceback (most recent call last):File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'math_score' >>>(2 動(dòng)態(tài)給類(lèi)添加屬性
類(lèi)屬性在其所有的對(duì)象中都生效。
執(zhí)行:(默認(rèn)所有對(duì)象的音樂(lè)成績(jī)?yōu)?0,當(dāng)然你也可以對(duì)其進(jìn)行修改)
''' 學(xué)習(xí)中遇到問(wèn)題沒(méi)人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書(shū)! ''' >>> from payhlib import Student >>> Student.music_score=60 >>> s1=Student('xiaoming',19) >>> s1.name 'xiaoming' >>> s1.age 19 >>> s1.music_score 60 >>> s2=Student('laowang',29) >>> s2.music_score 60 >>>2.動(dòng)態(tài)添加方法
當(dāng)類(lèi)或者對(duì)象的方法在需要增加的時(shí)候,對(duì)于不方便修改源碼的情況下,我們可以選擇動(dòng)態(tài)的對(duì)其添加方法。
(1 動(dòng)態(tài)給對(duì)象添加方法
給對(duì)象添加的方法只綁定在當(dāng)前對(duì)象上,不對(duì)其他對(duì)象生效,而且需要傳入self參數(shù)。
執(zhí)行:(通過(guò)types.MethodType方法給a對(duì)象綁定sayhi方法)
>>> from payhlib import Student >>> a=Student('xiaoming',17) >>> def sayhi(self): ... print('hi...') ... >>> a.sayhi() Traceback (most recent call last):File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'sayhi' >>> import types >>> a.sayhi=types.MethodType(sayhi,a) >>> a.sayhi() hi... >>> b=Student('laowang',27) >>> b.sayhi() Traceback (most recent call last):File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'sayhi' >>>(2 動(dòng)態(tài)給類(lèi)添加方法(類(lèi)方法和靜態(tài)方法)
給類(lèi)添加的方法對(duì)它的所有對(duì)象都生效,添加類(lèi)方法需要傳入self參數(shù),添加靜態(tài)方法則不需要。
執(zhí)行:(給類(lèi)添加靜態(tài)方法)
''' 學(xué)習(xí)中遇到問(wèn)題沒(méi)人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書(shū)! ''' >>> from payhlib import Student >>> stu = Student('xiaoming',16) >>> @staticmethod ... def staticHi(): ... print('staticHi...') ... >>> Student.hi=staticHi >>> stu.hi <function staticHi at 0x000001CB617F13A8> >>> stu.hi() staticHi... >>>執(zhí)行:(給類(lèi)添加類(lèi)方法)
因?yàn)轭?lèi)方法只能使用類(lèi)變量,所以我們?cè)黾右粋€(gè)類(lèi)變量home
class Student(object):home='china'def __init__(self,name,age):self.name=nameself.age=age>>> from payhlib import Student >>> stu = Student('xiaoming',17) >>> @classmethod ... def classHi(self): ... print(self.home) ... >>> Student.chi=classHi >>> stu.chi() china >>>3.限制給類(lèi)或?qū)ο筇砑拥膶傩?/strong>
假如我們只希望類(lèi)或者對(duì)象有name,age,score三個(gè)屬性,我們可以借助__slots__來(lái)做,而且無(wú)法添加其他屬性。
修改類(lèi):
''' 學(xué)習(xí)中遇到問(wèn)題沒(méi)人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書(shū)! ''' class Student(object):home='china'__slots__=('name','age','score') #init中變量必須在__slots__中def __init__(self,name,age):self.name=nameself.age=age執(zhí)行:
>>> from payhlib import Student >>> st = Student('xiaoming',16) >>> st.name 'xiaoming' >>> st.age 16 >>> st.score Traceback (most recent call last):File "<stdin>", line 1, in <module> AttributeError: score >>> st.score =100 >>> st.score 100 >>> st.phone='123' #無(wú)法添加phone屬性 Traceback (most recent call last):File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'phone' >>>多總結(jié)幾點(diǎn):
- 類(lèi)屬性是read-only的
- 靜態(tài)方法無(wú)法使用類(lèi)變量
- 類(lèi)方法只能使用類(lèi)變量,不能使用初始化變量
- __slots__數(shù)據(jù)類(lèi)型為元組
- __slots__只對(duì)當(dāng)前類(lèi)生效,對(duì)其子類(lèi)不生效
總結(jié)
以上是生活随笔為你收集整理的给Python的类和对象动态增加属性和方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 学Python一定要知道的十段经典代码
- 下一篇: Python 5种不为人知的高级特征