zoukankan      html  css  js  c++  java
  • 二 .反射

    # 反射:通过字符串来操作对象属性,类也是一样。
    class Foo:
        def __init__(self, name):
            self.name = name
    
        def eat(self):
            print('%s is eating' % self.name)
    
    
    obj = Foo('egon')
    
    print(hasattr(obj, 'eat'))  # 判断对象是否有eat属性,有返回True
    
    print(getattr(obj, 'age', None))  # 获取对象是否有age属性,没有返回设置的默认值None
    
    setattr(obj, 'age', 18)  # 当age不存在时候就是创建、存在就是需改
    print(obj.__dict__)  # {'age': 18, 'name': 'egon'}
    setattr(obj, 'age', 180)
    print(obj.__dict__)  # {'age': 180, 'name': 'egon'}
    
    #case
    class Ftp:
        def get(self):
            print('get')
    
        def put(self):
            print('put')
    
        def login(self):
            print('login')
    
        def run(self):
            while True:
                choice = input('>>:').strip()
                if hasattr(self, choice):
                    method=getattr(self,choice)
                    method()
                else:
                    print('命令不存在')
    
    
    obj = Ftp()
    obj.run()
    

      

  • 相关阅读:
    springboot-配置文件
    system--属性
    url--web路径
    jquery--遍历
    javascript---知识点2
    iframe
    linux--磁盘挂载
    jquery--插件
    javascript窗口宽高
    vue--知识点
  • 原文地址:https://www.cnblogs.com/yspass/p/9581326.html
Copyright © 2011-2022 走看看