反射是一個很重要的概念,它可以把字串映射到實體的變數或者實體的方法然后可以去執行呼叫、修改等操作,它有四個重要的方法:
1、getattr 獲取指定字串名稱的物件屬性
2、setattr 為物件設定一個物件
3、hasattr 判斷物件是否有對應的物件(字串)
4、delattr 洗掉指定屬性
1 # -*- coding:utf-8 -*- 2 def talk(self): # 定義一個函式 3 print("%s is talking..." % self.name) 4 class Dog(object): # 定義一個類 5 def __init__(self,name): 6 self.name = name 7 8 def eat(self): #定義一個eat的函式 9 print("%s is eating..." % self.name) 10 11 d = Dog("ssddda") # 實體化 12 choice = input("請隨意輸入>>>:") # 用戶輸入 13 print(hasattr(d, choice)) #判斷一個物件obj里是否有對應的name_str字串的方法 14 print(getattr(d,choice)) #根據字串去獲取obj物件里的對應的方法的記憶體地址 15 func = getattr(d,choice) 16 func() 17 if hasattr(d,choice): 18 '''choice為函式時''' 19 func = getattr(d,choice) 20 '''choice為變數時''' 21 # attr = getattr(d,choice) 22 # print(attr) 23 '''洗掉屬性或方法''' 24 delattr(d,choice) 25 x = getattr(d,choice) 26 print(d) 27 else: 28 setattr(d,choice,talk) # setattr(x,'y',z) 等價于 設定 x.y = z 29 func = getattr(d,choice) 30 func(d) 31 # setattr(d,choice,20) 32 # attr = getattr(d,choice) 33 # print(attr)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/67462.html
標籤:Python
下一篇:Python--例外
