代码如下,运行一下看看吧
def bulk(self):
print('%s is yeilling...'%self.name)
class Dog(object):
def __init__(self,name):
self.name = name
def eat(self):
print('%s eating ...'%self.name)
d = Dog('dog')
chioce = input('>>:').strip()
# print(hasattr(d,chioce)) #判断对象内部是否有这个方法,传入字符串形式,返回bool
# print(getattr(d,chioce))
# getattr(d,chioce)() #使用查到的方法,返回一个内存地址
if hasattr(d,chioce):
func = getattr(d,chioce)
func()
else:
setattr(d,chioce,bulk) #动态设置一个方法,但是这个方法提前写好了
new_func = getattr(d,chioce) #动态获取我设置的方法在类里面的名字
new_func(d) #然后执行这个方法,但是注意这个时候要将对象本身返回