Python動態繫結屬性和方法

2021-10-10 07:33:34 字數 2772 閱讀 2212

當我們定義了乙個 class,建立了乙個 class 的例項後,我們可以給該例項繫結任何屬性和方法,也可以給類繫結任何屬性和方法,這就是動態語言的靈活性。

給例項繫結屬性和方法,每個例項之間新增的部分是互不干擾的。

1. 先來看乙個方法:methodtype

如果我們在模組中定義乙個方法,而不是在類中定義乙個方法,那麼此時這個方法並不是物件的例項方法,但是我們可以將這個方法作為屬性賦值給物件的

某乙個屬性。比如下面這樣:

class

student

(object):

def__init___

(self, name, age)

: self.name = name

self.age = age

# 需要被繫結的方法

defrun

(self)

:print

("this is run method "

, self)

stu = student(

)stu.run = run

stu.run(

"******"

)# this is run method ******

當我們定義乙個 class 的時候可以給這個類定義例項屬性和例項方法,例項方法的特點:當例項方法被呼叫的時候python物件會自動作為self引數傳入

到方法的內部。但是在呼叫 run 方法的時候 stu 物件不會作為 self 引數傳遞到 run 方法內部,就好像是 staticmethod 方法一樣。methodtype 可以解決

這個問題,這個方法可以讓乙個模組方法在被呼叫的時候自動傳入呼叫物件作為 self 引數。語法如下:

anotherref = types.methodtype(methodname, instance/classname)
於是上面的**可以這樣改:

'''

'''from types import methodtype

class

student

(object):

def__init___

(self, name, age)

: self.name = name

self.age = age

# 需要被繫結的方法

defrun

(self)

:print

("this is run method "

, self)

stu = student(

)stu.run = methodtype(run, stu)

stu.run(

)# this is run method <__main__.student object at 0x000001b453cef370>

2. 下面我們來介紹下如何動態繫結

1) 繫結方法到例項中

from types import methodtype

class

student

(object):

pass

defset_age

(self, age)

: self.age = age

stu1 = student(

)stu2 = student()

stu1.set_age = methodtype(set_age, stu1)

stu2.set_age = methodtype(set_age, stu2)

stu1.set_age(22)

stu2.set_age(44)

print

(stu1.age)

# 22

print

(stu2.age)

# 44

2)繫結方法到類上

用 methodtype 將方法繫結到類,並不是將這個方法直接寫到類內部,而是在記憶體中建立乙個link指向外部的方法,在建立例項的時候這個link也會被複製。

'''

'''from types import methodtype

class

student

(object):

pass

defset_age

(self, age)

: self.age = age

student.set_age = methodtype(set_age, student)

stu1 = student(

)stu2 = student()

stu1.set_age(23)

stu2.set_age(99)

print

(stu1.age)

# 99

print

(stu2.age)

# 99

print(id

(stu1.set_age),id

(stu2.set_age)

)# 3022011453632 3022011453632

print(id

(stu1.age),id

(stu2.age)

)# 140718085415648 140718085415648

為什麼 stu1,stu2 都顯示的 99 呢?,因為 stu1 和 stu2 都指向了相同的 set_age 和 age 位址。

python 動態繫結屬性方法

import types 定義類 class person object num 0 def init self,name,age none self.name name self.age age def eat self print eat food 定義例項方法 def run self,spe...

python 動態繫結屬性與方法

動態繫結屬性與方法的意思就是在本沒有這個屬性與方法的例項物件中新增這個屬性與方法。具體操作如下 class stduent def init self,name,age self.name name self.age age defeat self print self.name 正在吃飯 std1...

Python學習系列之動態繫結屬性和方法(二十六)

動態繫結屬性和方法 python是動態語言,在建立物件之後,可以動態地繫結屬性和方法 1.動態地繫結屬性 示例 動態地繫結屬性 class student def init self,name,age self.name name self.age age 例項方法 def eat self pri...