zoukankan      html  css  js  c++  java
  • 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报错)
    
  • 相关阅读:
    babel的使用及安装配置
    npm install卡顿问题
    盒模型
    安全性
    字符串方法
    vue
    CSS3
    重载运算符
    装箱拆箱
    模板库
  • 原文地址:https://www.cnblogs.com/netflix/p/14855004.html
Copyright © 2011-2022 走看看