簡體   English   中英

如何在python 3.3中為命令創建快捷方式

[英]How To create a shortcut for a command in python 3.3

我剛剛開始學習python,想知道它們是否是一種捷徑代碼行的方法。 例如,我可以使用類似的東西嗎?

command = input()
if command = "create turtle"
    t =turtle.Pen()

要么

turtleCommand = input()
if turtleCommand = "circle"
    t.forward(100)
    t.left(91)

烏龜的事情只是假設的,如果一個字符串“輸入”(如果是一個單詞)激活了defineFunction

您可以編寫一個函數:

def draw_circle(t):
    t.forward(100)
    t.left(91)

然后調用它:

t = turtle.Pen()
command = input()

if command == "circle":
    draw_circle(t)
elif command = "stuff":
    ...

一個更可靠的解決方案是使用將命令映射到功能的字典:

commands = {
    "circle": draw_circle,
    "square": draw_square
}

然后按名稱獲取一個函數:

t = turtle.Pen()
turtle_command = input()
command = commands[turtle_command]

command(t)
def docircle(pen):
  pen.forward(100)
  pen.left(91)

commands = {
  'circle': docircle,
   ...
}

...

commands[turtleCommand](t)

您可以設置字典,將單詞映射到您希望單詞激活的功能:

commands = {'create turtle': create_turtle,
            'circle': circle, }

def create_turtle():
    t = turtle.Pen()

def draw_circle():
    ...

接着:

command = input()
commands[command]()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM