python基礎7 3 反射

2021-09-29 05:18:04 字數 3230 閱讀 3954

反射相關的四個函式hasattr、getattr、setattr、delattr,下面分別來演示每乙個函式的用法。

# author: mr.xue

# 2019.10.30

class

dog(

object):

def__init__

(self, name)

: self.name = name

defeat(self)

:print

("%s is eating..."

% self.name)

d = dog(

"d")

choice =

input

(">>"

)print

(hasattr

(d, choice)

)

測試結果如下:

xue@xue-macbookair:~/python_learn$ python3 fanshe.py 

>>:eat

true

xue@xue-macbookair:~/python_learn$ python3 fanshe.py

>>:talk

false

# author: mr.xue

# 2019.10.30

class

dog(

object):

def__init__

(self, name)

: self.name = name

defeat(self)

:print

("%s is eating..."

% self.name)

d = dog(

"d")

# 例項化

choice =

input

(">>:")if

hasattr

(d, choice)

: attr =

getattr

(d, choice)

# 去獲取choice方法的記憶體位址

print

(attr)

# 列印記憶體位址

attr(

)# 呼叫dog類的這個方法

測試結果如下:

xue@xue-macbookair:~/python_learn$ python3 fanshe.py 

>>:eat

.eat of <__main__.dog object at 0x7f81777e6588>>

d is eating.

..

# author: mr.xue

# 2019.10.30

defbulk

(self)

:# 類外部定義的乙個函式bulk

print

("%s is bulking..."

% self.name)

class

dog(

object):

# dog類

def__init__

(self, name)

: self.name = name

defeat(self)

:# 類內的方法

print

("%s is eating..."

% self.name)

d = dog(

"d")

# 例項化

choice =

input

(">>:"

)# 使用者輸入

ifhasattr

(d, choice)

:# 判斷d例項是否有choice方法

pass

else

:# 沒有

# 第一種:針對函式

# 給d物件新增使用者輸入的方法choice,方法功能實現和bulk一樣

setattr

(d, choice, bulk)

d.talk(d)

# 假如使用者輸入『talk』,這裡是呼叫talk方法

# 第二種:針對變數

setattr

(d, choice,22)

# 給d例項新增乙個變數choice,值等於22

print

(getattr

(d, choice)

)# 列印choice的值

輸出測試結果如下:

xue@xue-macbookair:~/python_learn$ python3 fanshe.py 

>>:talk

d is bulking...

22

# author: mr.xue

# 2019.10.30

class

dog(

object):

def__init__

(self, name)

: self.name = name

defeat(self)

:print

("%s is eating..."

% self.name)

d = dog(

"d")

choice =

input

(">>:"

)print

(hasattr

(d, choice)

)# 在刪除之前,看看方法還在不在

ifhasattr

(d, choice)

:# 有這個方法

delattr

(d, choice)

# 刪除這個方法

print

(hasattr

(d, choice)

)# 再次列印檢視方法還在不在

測試輸出結果如下:

xue@xue-macbookair:~/python_learn$ python3 fanshe.py 

>>:eat

true

traceback (most recent call last):

file "fanshe.py"

, line 18, in delattr(d, choice)

attributeerror: eat

python基礎 反射

反射 name alex name class teacher dic def show student self print show student def show teacher self print show teacher classmethod def func cls print h...

python基礎學習 反射

所謂的反射,就是通過字串去訪問類或物件成員,比如如果乙個student類有乙個name物件屬性,那麼就可以通過乙個 name 字串去訪問student物件的name屬性 如python可以通過hasattr 函式來獲取乙個物件是否有某個屬性 class student def init self,n...

python基礎 反射和異常

反射 通俗的說就是你給乙個字串,我就能匹配到和字串相同的函式進行呼叫 反射舉例說明 def bulk self print s is yelling self.name class dog object def init self,name self.name name defeat self,fo...