zoukankan      html  css  js  c++  java
  • Python中实现switchcase

    
    
    # 第一种方式使用python中的字典
    # author:wanstack

    def first_func():
    print('first_func')

    def second_func():
    print('second_func')

    def third_func():
    print('third_func')

    def fourth_func():
    print('fourth_func')

    menu = """
    ##############################
    1. 选择第一个函数
    2. 选择第二个函数
    3. 选择第三个函数
    4. 选择第四个函数
    ##############################
    """
    print(menu)
    choice = input('Please input your choice:')
    # dict_menu = {"1" : first_func,
    # "2" : second_func,
    # "3" : third_func,
    # "4" : fourth_func
    # }
    # print(type(choice))
    # dict_menu[choice]()

    list_menu = [first_func,second_func,third_func,fourth_func]
    choice = int(choice)
    dict_menu = {}
    for index,item in enumerate(list_menu):
    # print(index,item)
    dict_menu[index] = item

    dict_menu[choice]()
    
    

     第二种方式使用反射

    python中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr,改四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。

    class Foo(object):
     
        def __init__(self):
            self.name = 'wupeiqi'
     
        def func(self):
            return 'func'
     
    obj = Foo()
     
    # #### 检查是否含有成员 ####
    hasattr(obj, 'name')
    hasattr(obj, 'func')
     
    # #### 获取成员 ####
    getattr(obj, 'name')
    func = getattr(obj, 'func')
    func()
    # #### 设置成员 #### setattr(obj, 'age', 18) setattr(obj, 'show', lambda num: num + 1) # #### 删除成员 #### delattr(obj, 'name')
    生活不会突变,你要做的只是耐心和积累。人这一辈子没法做太多的事情,所以每一件都要做得精彩绝伦。你的时间有限,做喜欢的事情会令人愉悦,所以跟随自己的本心。
  • 相关阅读:
    How to change hostname on SLE
    How to install starDIct on suse OS?
    python logging usage
    How to reset password for unknow root
    How to use wget ?
    How to only capute sub-matched character by grep
    How to inspect who is caller of func and who is the class of instance
    How to use groovy script on jenkins
    Vim ide for shell development
    linux高性能服务器编程 (二) --IP协议详解
  • 原文地址:https://www.cnblogs.com/wanstack/p/7052874.html
Copyright © 2011-2022 走看看