有没有办法镜像 python 函数?

Is there a way to mirror a python function?

我是第一个 python class 的学生,我们正在使用 Turtle 绘制图像。为了节省时间,我正在尝试创建一个镜像函数,该函数可以将一个函数结果在 y 轴上翻转给定的像素数。为了简单起见,我创建了一些函数来加速我的编码。以下是我的代码的工作原理:

units, north, east, south, west = desiredPixelsPerUnit, 90, 0, 270, 180

def main():
    eye(30, 15)
    eye(40, 15)

def left():
    myTurtle.left(90)
def draw(count):
    distance = units * count
    myturtle.forward(distance)
def singleStep(xDirection, yDirection, stepCount):
    down()
    for step in range(stepCount):
        if yDirection == north:
            point(north)
            draw(1)
            if xDirection == east:
                point(east)
                draw(1)
         etc..
def eye(xPosition, yPosition):
    ....
    draw(3)
    left()
    draw(2)
    left()
    ....
    singleStep(east, north, 1)
    singleStep(west, north, 2)
    etc....

所有这一切给了我以下

两次运行宁eye()的结果:

我要创建的是一个传递给另一个函数的函数,然后将查看正在执行的内容。如果是left()right()运行则相反。如果是点(x, y)180tox。如果它在函数内部有一个函数调用,那么它也会检查它的左或右。像这样。

def mirror(function):
    for action in function:
        if action == left():
            execute right()
        ...
        elif action == singleStep():
            newFunction = singleStep()
            for action in newFunction:
                if:
                    statement above
                else:
                    statement below
       else:
           execute initial action

我对编码和编程还是很陌生。我尝试过使用数组、关联数组和列表,使用 eval 等等。花在弄清楚上的时间比写一个单独的左右指令列表的时间要长得多哈哈,但我真的很想弄清楚如何做这样的事情。

您可以退后一步,不要直接调用 left()right()。只需创建您自己的函数 your_left()your_right() 并每次都使用它们。然后使用名为 mirror 的全局变量。这个变量将作为你的标志。因此,当您想要镜像输出时,只需将 mirror 设置为 True

您的函数 your_right()your_left() 看起来像这样:

def your_right():
    left() if mirror else right()

def your_left():
    right() if mirror else left()

然后您可以随意镜像所有输出,如果您愿意的话。希望能帮到你!

下面是如何使用 yield:

import turtle

def function(): # Your function here, with the action calls replaced with yielding the un-called action, along with the argument
    for _ in range(4):
        yield turtle.forward, 100
        yield turtle.right, 90

def mirror(function):
    actions = {turtle.right: turtle.left,
               turtle.left: turtle.right,
               turtle.forward: turtle.backward,
               turtle.backward: turtle.forward}
    for action, argument in function():
        actions[action](argument)

mirror(function)

分解:

  1. 定义将传递给mirror函数的函数时, 不要调用乌龟命令。相反,使用 yield 产生函数和参数 作为元组,这样 mirror 函数将能够访问应该调用的函数。

  2. mirror函数中,定义一个乌龟命令字典,actions,用于镜像。

  3. 遍历传递到mirror函数括号中的函数产生的乌龟动作,并将元组解压成action, argument对以用于镜像。