###反射## getattr,hasattr,setattr,delattr,和類裡面的欄位有關,具體看例子 #1 class Person: def __init__(self,name,age): self.name = name self.age = age def show_lover(s ...
###反射
## getattr,hasattr,setattr,delattr,和類裡面的欄位有關,具體看例子
#1 class Person: def __init__(self,name,age): self.name = name self.age = age def show_lover(self): print('lover') o = Person('x',21) b = 'name' print(o.__dict__[b]) # 2 b = input('>>>') if hasattr(o,b): v = getattr(o,b) # 去什麼東西裡面獲取什麼內容 delattr(o,b) setattr(o,'age',21) print(v) func=getattr(o,'show_lover') # 拿到方法 func()View Code
# 3 拿到類對象的欄位
class Person: stat = '123' def __init__(self,name,age): self.name = name self.age = age r = getattr(Person,'stat') print(r)
# 4拿到其他模塊的函數和欄位等
# s.py NAME = '_nbloser' def func(): return'func' class Person: def __init__(self): self.name = '_nbloser'
# 執行.py import s r1 = getattr(s,'NAME') r2 = getattr(s,'func') Pers = getattr(s,'Person') p1 = Pers() print(r1,r2(),p1.name) # _nbloser func _nbloser
# 應用小例子
def f1(): return'首頁' def f2(): return'新聞' def f3(): return'精華' import s inp = input('>>') if hasattr(s,inp): func = getattr(s,inp) print(func()) else: print(404)