def talk(self): print("%s is talking"%self.name) class Dog(object): def __init__(self, name): self.name = name def eat(self): print("%s is eating %s" % (self.name, "baozi")) d = Dog("cql") choice = input("input>>") if hasattr(d,choice): #hasattr:判斷類Dog裏是否有對應的字符串的方法或者屬性 func = getattr(d,choice) #getattr:根據字符串去獲取Dog類裏的對應的方法的內存; getattr(x, 'y') is equivalent to x.y func() else: #若是類中沒有該方法或者屬性 # setattr(d,choice,talk) #給Dog類新增一個方法,d.choice-->talk(self),choice是根據用戶輸入動態變化;setattr(x, 'y', v) is equivalent to ``x.y = v'' # func = getattr(d,choice) # func(d) setattr(d,choice,None) #給Dog類新增一個屬性,d.choice-->None,choice是根據用戶輸入動態變化 v = getattr(d,choice) print(v)