1. 程式人生 > 實用技巧 >Python--反射

Python--反射

反射是一個很重要的概念,它可以把字串對映到例項的變數或者例項的方法然後可以去執行呼叫、修改等操作。它有四個重要的方法:

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)