【问题标题】:Can you use the name of a turtle in the parameters of a variable?你能在变量的参数中使用乌龟的名字吗?
【发布时间】:2022-11-22 06:10:07
【问题描述】:
import turtle as trtl
def position(hold):
  hold.forward(200)

position('trtl')

我试图让一个有多个海龟的程序在所有海龟之间使用类似的功能,是否可能像图像中显示的那样?

【问题讨论】:

  • 需要包含足够的信息来回答问题在问题本身的正文中遵守minimal reproducible example规则。代码不应出现在屏幕截图中;见Why should I not upload images of code/data/errors?
  • ...现在已经解决了——直接的问题是如果你运行import turtle as trtl1; import turtle as trtl2trtl1trtl2都是同一只乌龟;它们只是对模块缓存中相同条目的引用,所以它根本不是“多只海龟”。
  • 请注意,turtle 模块让您实例化单独的海龟,但是(1)您需要实际执行此操作; (2) 为什么要传递名称而不是对象?
  • (明确地说,你能够以按名称传递它们的方式跟踪它们,但这会使您的代码更复杂并且更慢;我们的范围仅限于实际的,可回答的问题,所以我问的是您希望通过传递字符串而不是直接引用对象获得什么实际价值)
  • 只需将 turtle 实例传递给函数即可。

标签: python turtle-graphics


【解决方案1】:

如果你想通过名称来引用事物,将它们存储在字典中;使用名称作为键。

import turtle

turtles = {
  "one": turtle.Turtle(),
  "two": turtle.Turtle(),
}

def position(turtle_name):
  return turtles[turtle_name].forward(200)

position('one')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 2018-09-04
    • 2017-08-09
    • 1970-01-01
    相关资源
    最近更新 更多