python中对象调用功能的开关实现

问题描述

我正在尝试在Python中的Dictionary中实现切换。但是当我调用方法
chooices.get(x,“这不是程序”)它调用语句中的所有Function,而不是调用x function。

我已经阅读了此实现 Replacements for switch statement in Python?

但是对于我来说这没有帮助,因为我的函数具有打印语句

文件包含代码

#include<iostream>
using namespace std;
class base1
{
    public:
    int a;
    void geta()
    {
        cout<<"enter value of a: "; 
        cin>>a;
    }
};
class base2
{
    public:
    int b;
    void getb()
    {
        cout<<"enter value of b: ";
        cin>>b;
    }
};
class child : public base1,public base2
{
    public:
    void sum()
    {
        cout<<"Sum of a and b is: "<<a + b;
    }
};

int main()
{
     child c;
     c.geta();
     c.getb();
     c.sum();
     return 0;
}

第1天的课程包含代码

from  Day1.Day1 import Day1
from Day2.TipCalculator import TipCalculator


def choose():
    print("Choose From the following Program:\n")
    day1 = Day1()
    day1.day1()

    day2 = TipCalculator()
    day2.day2()


    x = int(input());


    chooices={
        1: day1.program1(),2: day2.program1(),}
    chooices.get(x,"Ther is no program")    

choose()

提示计算器代码

class Day1:

    def day1(self):
        print('1. Band name Generator\n')

    def program1(self):
        print('Welcome to Band Name Generator.\n')
        cityName=input('What\'s is the name of city you grew up?\n')
        petName = input('What\'s your pet\'s name?\n')
        print('Your Band Name Could be : '+cityName+" "+petName)

我只需要switch语句的实现,该语句就像switch一样调用Requested Program。我知道可以通过If-else实现,但是字典映射似乎也是switch的不错选择

解决方法

概述:解释器为子函数使用的非局部变量创建一个闭包。在此示例中,子变量value为22,并存储在闭合单元格中。

  def parent(arg_1,arg_2):
  value=22
  my_dict = {'chocolate':'yummy'}
  def child():
    print(2*value)
    print(my['chocolate'])
    print(arg_1 + arg_2)
   return child

  new_function=parent(3,4)

  print(cell.cell_contents for cell in new_function.__closure__])
,

如果您没有很多变体,可以使用 switch 的辅助函数简化 if/elif/else 语句。这只是语法糖果,但对于小值集可能就足够了。

def switch(v): yield lambda *c: v in c

示例用法:

x = int(input())
for case in switch(x):
    if   case(1): day1.program1()
    elif case(2): day2.program1()
    else:         print("there is no program")

支持同一个方法调用的多个值:

x = int(input())
for case in switch(x):
    if   case(1,5):   day1.program1()
    elif case(2,3,4): day2.program1()
    else:             print("there is no program")

你也可以用更像 C 的风格来使用它

x = int(input())
for case in switch(x):

    if case(1,5):   
       day1.program1()
       break

    if case(2,4): 
       day2.program1()
       break
else:
    print("there is no program")