hasattr,getattr,setattr和delattr

'''
反射
'''
def add(self):
    print("我是新绑定的方法!")

class People(object):
    skin = "yellow"
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say(self, content):
        print("说了[%s]" % content)


choice = input(">>").strip()

# if choice in People.__dict__:
#     print("有此方法")
# print(People.__dict__)   #打印所有类属性和方法

# p = People("小白", "26")
# print(p.__dict__)          #打印所有的实例属性
p = People("小白", "26")

if hasattr(p, choice):
    #如果是方法,直接执行
    try:
        func = getattr(p, choice)
        func("打工不可能打工的!")  
    #输入是属性,则会报TypeError,则直接打印得到属性值
    except TypeError as e:
        print(func)
else:
    setattr(p, choice, add)
    func = getattr(p, choice)
    func(p)
#delattr(p, choice)     #删除属性和方法

  

猜你喜欢

转载自www.cnblogs.com/ericbai/p/8964476.html