python類的反射
阿新 • • 發佈:2017-08-27
elf line 調用方法 cnblogs choice file 是你 back pri
反射
通過字符串映射或者修改程序運行時的狀態、屬性、方法, 有一下4個方法
小例子--根據用戶輸入調用方法:
class Dog(object): def __init__(self,name): self.name = name def eat(self): print("%s is eating..",self.name) d= Dog(‘二哈‘) choice = input(">>:").strip() d.choice() =========執行結果=========== >>:eat Traceback (most recent call last): File "E:/pywww/day06/11.py", line 13, in <module> d.choice AttributeError: ‘Dog‘ object has no attribute ‘choice‘
這裏用戶輸入的只是一個字符串,所以不會把輸入的內容當作類的方法執行。
最原始的辦法就是加個判斷,然後判斷輸入的字符串是不是在這個類裏有這個方法,但是這種靈活度不好。所以可以用到下面這種方法。
hasattr(obj,name_str)
輸入一個字符串,判斷對象有沒有這個方法。
class Dog(object): def __init__(self,name): self.name = name def eat(self): print("%s is eating.."% self.name) d= Dog(‘二哈‘) choice = input(">>:").strip() #eat print(hasattr(d,choice)) #True
getattr(obj,name_str)
如果是方法返回對象的內存地址,如果是屬性直接返回該屬性的值
print(getattr(d,choice)) #<bound method Dog.eat of <__main__.Dog object at 0x0000000000A72358>>
如果是一個不存在的方法會報錯:AttributeError: ‘Dog‘ object has no attribute ‘aa‘
既然是地址就說明加上括號就可以調用了:
class Dog(object): def __init__(self,name): self.name = name def eat(self): print("%s is eating.."% self.name) d= Dog(‘二哈‘) choice = input(">>:").strip() #eat getattr(d,choice)() #二哈 is eating..
以上兩個方法可以組合起來使用:
if hasattr(d,choice): getattr(d,choice)() #二哈 is eating..
也可以賦值給一個變量,然後傳參給方法
class Dog(object): def __init__(self,name): self.name = name def eat(self,food): print("%s is eating.."% self.name,‘ like ‘,food) d= Dog(‘二哈‘) choice = input(">>:").strip() #eat if hasattr(d,choice): func = getattr(d,choice) func(‘包子‘) #二哈 is eating.. like 包子
setattr(x,‘y‘,v) x.y = v
添加一個方法
def bulk(self): #先定義要添加的方法 print(‘%s wang wang wang‘ % self.name) class Dog(object): def __init__(self,name): self.name = name def eat(self,food): print("%s is eating.."% self.name,‘ like ‘,food) d= Dog(‘二哈‘) choice = input(">>:").strip() #bulk if hasattr(d,choice): func = getattr(d,choice) func(‘包子‘) else: setattr(d,choice,bulk) d.bulk(d) #bulk 是你輸入的字符串 ,這裏要把d傳進去,不然提示你少傳一個參數進去
上面是動態裝載一個方法,也可以動態裝載一個屬性
setattr(d,choice,22) #age print(getattr(d,choice)) #22
delattr(obj,name_str)
動態刪除屬性或方法
delattr(d,choice)
python類的反射