day07_07 反射

__author__ = "Alex Li"

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("NiuHanYang")
choice = input(">>:").strip()

if hasattr(d,choice):
    # 1.判断方法存在(eat)
    # print(getattr(d,choice))
    # func = getattr(d,choice)
    # func("ChenRonghua")

    # 2.判断属性存在(输入name)
    attr = getattr(d,choice)
    setattr(d,choice,"Ronghua")
    print(d.name)

    # 3.判断属性存在(输入name),并删除
    # delattr(d,choice)
    # print(d.name)       #'Dog' object has no attribute 'name'
else:
    # 1.新增加类方法(talk)
    setattr(d,choice,bulk) #d.talk = bulk
    func = getattr(d,choice)    #输入任意非eat的方法都能相当于bulk
    func(d)

    # 2.新增加类属性(输入非name的类属性)
    # setattr(d,choice,22)
    # print(getattr(d, choice))
    # print(d.age)    #(输入age,输入非age报错)
原文地址:https://www.cnblogs.com/netflix/p/14855004.html