Python之反射練習

2021-09-07 16:35:51 字數 711 閱讀 4282

#

什麼是反射?可以用字串的方式去訪問物件的屬性

class

test():

_name = "

sss"

deffun(self):

return

"helloword

"t =test()

#print(hasattr(t,"_name")) #hasattr(obj,name)#檢視類裡面有沒有name屬性

#print(hasattr(t,"fun")) #true

if hasattr(t,"

_name"):

print(getattr(t,"

_name

")) #

sssif hasattr(t,"

fun"

):

print(getattr(t,"

fun")()) #

helloword

ifnot hasattr(t,"

age"): #

如果屬性不存在

print("

沒有該屬性和方法,我來給設定乙個")

setattr(t,

"age

","18

") #

給t物件設定乙個預設值,預設age=18

print(getattr(t,"

age"))

python之反射機制

匯入模組方式 單層匯入 import os import os 多層匯入 from util.excel import excel import util.excel.excel fromlist true 如果不加上fromlist true,只會匯入list目錄 反射方式 反射即想到4個內建函式...

Python 入門 之 反射

反射主要是指程式可以訪問 檢測和修改它本身狀態或行為的一種能力 自省 1 getattr 獲取 2 setattr 設定 3 hasattr 判斷是否存在 4 delattr 刪除class a def init self,name self.name name def func self prin...

java反射練習

public class mytest public mytest int k,string s,boolean b,double d private static final string str public int a private double c private boolean s pr...