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()
    

      

  • 相关阅读:
    Remove Element
    C++ 一些STL
    Two Pointers/hash/3Sum/4Sum类题目
    动态规划
    UVa 12657 双向链表
    并行运行环境
    多线程编程
    HTML XML CSS JS 迅速学习
    UVa 11988 数组模拟链表
    静态链表
  • 原文地址:https://www.cnblogs.com/yspass/p/9581326.html
Copyright © 2011-2022 走看看