Python的動態屬性和方法

通常我們會將程式語言分為靜態和動態。靜態語言的變數是在記憶體中的有型別的且不可變化的,除非強制轉換它的型別;動態語言的變數是指向記憶體中的標籤或者名稱,其型別在程式碼執行過程中會根據實際的值而定。Python就是典型的動態語言。

1、動態新增屬性

當類或者物件的屬性在需要增加的時候,對於不方便修改原始碼的情況下,我們可以選擇動態的對其新增屬性。

1.1、動態給物件新增屬性

物件屬性只在當前物件生效,在其他物件中是無法呼叫的。

定義一個類:

class Student(object): def __init__(self,name,age): self。name=name self。age=age

執行:(給例項新增數學成績屬性並且初始化)

>>> from payhlib import Student >>> s=Student(‘phyger’,18) >>> s。name‘phyger’>>> s。age18>>> s。math_score=100>>> s。math_score 100>>> ss=Student(‘xiaopang’,28)>>> ss。name‘xiaopang’>>> ss。age 28>>> ss。math_scoreTraceback (most recent call last): File “”, line 1, in AttributeError: ‘Student’ object has no attribute ‘math_score’>>>

1.2、動態給類新增屬性

類屬性在其所有的物件中都生效。

執行:(預設所有物件的音樂成績為60,當然你也可以對其進行修改)

>>> from payhlib import Student>>> Student。music_score=60>>> s1=Student(‘phyger’,19) >>> s1。name‘phyger’>>> s1。age19>>> s1。music_score60>>> s2=Student(‘xiaopang’,29)>>> s2。music_score60>>>

2、動態新增方法

當類或者物件的方法在需要增加的時候,對於不方便修改原始碼的情況下,我們可以選擇動態的對其新增方法。

2.1、動態給物件新增方法

給物件新增的方法只繫結在當前物件上,不對其他物件生效,而且需要傳入self引數。

執行:(透過types.MethodType方法給a物件繫結sayhi方法)

>>> from payhlib import Student>>> a=Student(‘phyger’,17) >>> def sayhi(self):。。。 print(‘hi。。。’)。。。 >>> a。sayhi()Traceback (most recent call last): File “”, line 1, in AttributeError: ‘Student’ object has no attribute ‘sayhi’>>> import types >>> a。sayhi=types。MethodType(sayhi,a)>>> a。sayhi()hi。。。>>> b=Student(‘xiaopang’,27) >>> b。sayhi()Traceback (most recent call last): File “”, line 1, in AttributeError: ‘Student’ object has no attribute ‘sayhi’>>>

2.2、動態給類新增方法(類方法和靜態方法)

給類新增的方法對它的所有物件都生效,新增類方法需要傳入self引數,新增靜態方法則不需要。

執行:(給類新增靜態方法)

>>> from payhlib import Student >>> stu = Student(‘phyger’,16)>>> @staticmethod。。。 def staticHi():。。。 print(‘staticHi。。。’)。。。 >>> Student。hi=staticHi >>> stu。hi>>> stu。hi()staticHi。。。>>>

執行:(給類新增類方法)

因為類方法只能使用類變數,所以我們增加一個類變數home

class Student(object): home=‘china’ def __init__(self,name,age): self。name=name self。age=age

>>> from payhlib import Student>>> stu = Student(‘phyger’,17) >>> @classmethod 。。。 def classHi(self): 。。。 print(self。home)。。。 >>> Student。chi=classHi>>> stu。chi()china>>>

3、限制給類或物件新增的屬性

假如我們只希望類或者物件有name,age,score三個屬性,我們可以藉助__slots__來做,而且無法新增其他屬性。

修改類:

class Student(object): home=‘china’    __slots__=(‘name’,‘age’,‘score’)   #init中變數必須在__slots__中 def __init__(self,name,age): self。name=name self。age=age

執行:

>>> from payhlib import Student>>> st = Student(‘phyger’,16)>>> st。name ‘phyger’>>> st。age 16>>> st。scoreTraceback (most recent call last): File “”, line 1, in AttributeError: score>>> st。score =100>>> st。score 100>>> st。phone=‘123’      #無法新增phone屬性Traceback (most recent call last): File “”, line 1, in AttributeError: ‘Student’ object has no attribute ‘phone’>>>

多總結幾點:

類屬性是read-only的

靜態方法無法使用類變數

類方法只能使用類變數,不能使用初始化變數

__slots__資料型別為元組

__slots__只對當前類生效,對其子類不生效

Python的動態屬性和方法

點選↓↓↓