Python TypeError:' function'当我尝试实现switch case时,object在嵌套函数中是不可订阅的

时间:2018-02-05 09:29:24

标签: python random switch-statement

我正在尝试在3台机器之间编写一个随机决策。 由于Python没有任何开关/案例功能,我使用了ifelif

每台机器(line1(),line2(),line3())也有自己的功能。 但是,我一直在犯错。

请告诉我出了什么问题。

machine_choice = [1,2,3]
selected_machine = random.choice(machine_choice)
print(selected_machine)

def machines(selected_machine):
    if selected_machine == 1:
        print("machine 1 randomly selected")
        line1()
    elif selected_machine == 2:
        print("machine 2 randomly selected")
        line2()
    else:
        print("machine 3 randomly selected")
        line3()

machines(selected_machine)

def line1():
if machine1["hardness"] < rev[i][1]["condition"]:
        print("\tMachine 1 hardness breached, will take 30mins for changing the system")
        machine1["hardness"] = 10

        time = line1
        machine1["schedule"].append([d,"machine 1",time,"change",30.,time.add(minutes=30)])
        print("\tno activities from {} to {}".format(time,time.add(minutes=30)))
        time = time.add(minutes=30)
        print("\tdone changing at time: ",time)
        print("\tcurrent log: ",machine1["schedule"],"\n")
        d+=1

        line1=time
        #line1 = max(time,line1,line2)
        machine1["schedule"].append([d,"machine 1",line1,"feeding",5.,line1.add(minutes=5)])
        line1 = line1.add(minutes=5)
        d+=1
        machine1["schedule"].append([d,"machine 1",line1,rev[i][0],rev[i][1]["duration"],line1.add(minutes=rev[i][1]["duration"])])
        line1 = line1.add(minutes=rev[i][1]["duration"])
        time = time.add(minutes=5)

        d+=1

        if rev[i][1]["quantity"] == 0:
            i += 1

2 个答案:

答案 0 :(得分:2)

  

我正在尝试在3台机器之间编写随机决策。

在Python中,函数没有什么特别之处,你可以像使用任何其他对象一样使用它们。

def machine_one():
  return 'Machine One'

def machine_two():
  return 'Machine Two'

def machine_three():
  return 'Machine Three'

machines = [machine_one, machine_two, machine_three]

print(random.choice(machines)())

答案 1 :(得分:0)

该消息意味着您尝试访问定义为函数的某个python对象,就好像它是一个数组一样。看起来像您提供的代码的最可能的候选者是machine_choice。

但请提供一个有用的最小例子,在这种情况下意味着包括导入必要的模块(随机)和行功能。

关于代码的目的(伪造开关),级联if解决方案通常不是一个非常好的解决方案。将random.choice与数组或字典或带有随机数的数组作为键或索引使用会更加pythonic。

同样使用switch是OO编程中的常见代码气味,通常最好使用对象多态性和工厂替换。

您可以查看python switch replacement了解详情。