【问题标题】:Function inconsistent in requirements功能不符合要求
【发布时间】:2015-11-28 15:26:33
【问题描述】:

我只是在使用“Think Python”一书学习编码,我很困惑。我遇到的问题是在 TurtleWorld 中创建花朵。我正在创建的功能在其要求上并不一致。首先让我发布实际工作的成品:

from swampy.TurtleWorld import*

world=TurtleWorld()
bob=Turtle()
print bob
bob.delay=.001

def polyline(t,n,length,angle):
    t=Turtle 
    print t
    for i in range(n):
        fd(bob,length)
        lt(bob,angle)

def arc(t, r, angle):
    t=Turtle
    arc_length=2*math.pi*r*angle/360
    n=int(arc_length/3)+1
    step_length=arc_length/n
    step_angle=float(angle)/n
    polyline(t,n,step_length,step_angle)

def petal(t,r,angle):
    for i in range(2):
        arc(t,r,angle)
        lt(t,180-angle)

def flower(t, n, r, angle):
    t=Turtle
    for i in range(n):
        petal(bob,r,angle)
        lt(bob,360/n)

flower(bob,5,77,99)

wait_for_user

arcpetal的函数定义上,t对于turtle来说已经足够了,虽然我开始的时候,在flowerpolyline的定义中使用t返回了一个错误unbound method(fd和lt)。需要海龟实例,而是获得类型实例。

添加到一半函数定义中的t=Turtleprint turtle 是在事后添加的,以尝试修复此错误。这是工作版本,我只是想知道为什么它以前不起作用。我什至不确定为什么会这样,因为我主要是因为沮丧而将bob 放入t,我实际上并没有期望它会起作用。

【问题讨论】:

  • bob = Turtle()bob 设置为 Turtle 函数的评估结果。尝试bob = Turtle(注意没有括号)并删除对 t 的函数内分配。

标签: python turtle-graphics


【解决方案1】:

虽然我在下面使用 Python 提供的海龟库,而不是 swampy.TurtleWorld,但我认为这对您遇到的问题没有影响。您似乎对函数调用中的形参以及函数调用和方法调用之间的区别有一个基本的误解。考虑一下这一系列事件:

flower(bob,5,77,99)
def flower(t, n, r, angle):
    t=Turtle
    ...

这里有一个非常好的乌龟bob,作为乌龟参数t 传入,只是立即被其他东西替换。或者考虑polyline,它有一个乌龟参数t,但是当需要乌龟时使用全局bob。以下是我对你的程序应该如何组合的设想:

from turtle import Turtle, Screen
from math import pi

def polyline(turtle, n, length, angle):
    for _ in range(n):
        turtle.fd(length)
        turtle.lt(angle)

def arc(turtle, radius, angle):
    arc_length = 2 * pi * radius * angle / 360
    n = int(arc_length / 3) + 1
    step_length = arc_length / n
    step_angle = float(angle) / n
    polyline(turtle, n, step_length, step_angle)

def petal(turtle, radius, angle):
    for _ in range(2):
        arc(turtle, radius, angle)
        turtle.lt(180 - angle)

def flower(turtle, n, radius, angle):
    for _ in range(n):
        petal(turtle, radius, angle)
        turtle.lt(360 / n)

screen = Screen()

bob = Turtle()

flower(bob, 5, 77, 99)

screen.exitonclick()

输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2021-06-17
    • 2019-02-06
    • 1970-01-01
    相关资源
    最近更新 更多