反射

#Author:lei
def bulk(self):
    print("%s is yielling..."%self.name)


class Dog(object):
    def __init__(self,name):
        self.name=name

    def eat(self,food):
        print("%s is eating %s..."%(self.name,food))


d = Dog("niuhanyang")
choice=input(">>:").strip()
print(hasattr(d,choice)) #判斷輸入的 choice值是不是在d對象裏對應的方法字符,在就爲true

#print(getattr(d,choice)) #映射出chioce對應的對象內存地址

#getattr(d,choice)()  #加上括號就是調用對象裏 eat的方法,choice值=eat字符

#if hasattr(d,choice): #判斷 choice值和eat字符對應
#    getattr(d,choice)() #調用 d.eat() 獲取對象內存地址,調用對象內存地址執行對象

if hasattr(d,choice):
   # delattr(d,choice) 刪除實例變量或方法,後面不在引用 比如 d,eat 後面就不能用d.eat()
    func=getattr(d,choice)
    func("baozi")  #baozi對應food

else:
    setattr(d,choice,bulk) #將d對象外面的bulk方法添加到d裏的對象方法, 相當於外面的方法動態裝備到類裏
    d.talk(d) #d對象添加bulk之後將方法重命名爲talk,運行talk需要傳d對象進去,相當於外面的方法動態裝備到類裏

#----------------------------------------------------
def bulk(self):
    print("%s is yielling..."%self.name)


class Dog(object):
    def __init__(self,name):
        self.name=name

    def eat(self,food):
        print("%s is eating %s..."%(self.name,food))


d = Dog("niuhanyang")
choice=input(">>:").strip()
print(hasattr(d,choice)) #判斷輸入的 choice值是不是在d對象裏對應的方法字符,在就爲true

#print(getattr(d,choice)) #映射出chioce對應的對象內存地址

#getattr(d,choice)()  #加上括號就是調用對象裏 eat的方法,choice值=eat字符

#if hasattr(d,choice): #判斷 choice值和eat字符對應
#    getattr(d,choice)() #調用 d.eat() 獲取對象內存地址,調用對象內存地址執行對象

if hasattr(d,choice): #判斷 如果是否存在 判斷name
   # attr=getattr(d,choice)  #獲取對象內存地址
    setattr(d,choice,"Ronghua")  #那麼就改成"Ronghua",name是存在的,那麼 d.name="Ronghua"  設置修改name
#變量不能調用,只能引用
else:
    setattr(d,choice,22)  #新創建的變量賦值22,所以返回22,變量名是動態的,固定值22
    #func=getattr(d,choice) 如果22是函數名
    #func(d)
    print(getattr(d,choice))
print(d.name) #setattr(d,choice,"Ronghua") #輸入的choice如果爲name,就對應爲"Ronghua"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章