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