通过字符串映射或修改程序运行时的状态、属性、方法。
四个方法
getattr(object, name, default=None)
hasattr(object, name)
setattr(x, y, v)
delattr(x, y)
hasattr(object, name, default=None)
判断一个对象中是否有对应的字符串的方法映射
getattr(object, name)
根据字符串去获取obj对象里的对应的方法
setattr(x, y, v)
设置属性
delattr(x, y)
删除属性
# Author:dancheng
def bulk(self):
print("%s is yelling..." %self.name)
class Dog(object):
def __init__(self, name):
self.name = name
def eat(self, food):
print("%s is eating..." %self.name, food)
d = Dog("dhe")
choice = input(">>:").strip()
if hasattr(d, choice):
func = getattr(d, choice)
func("hah")
else:
setattr(d, choice, bulk)
func = getattr(d, choice)
func(d)