思考Python——练习4.3#2

思考Python——练习4.3#2,python,Python,这些就是问题所在。我成功地完成了问题1,但我只是添加它作为背景。我在第二个问题上有困难 1. Write a function called square that takes a parameter named t, which is a turtle. It should use the turtle to draw a square. Write a function call that passes bob as an argument to square, and then run t

这些就是问题所在。我成功地完成了问题1,但我只是添加它作为背景。我在第二个问题上有困难

1. Write a function called square that takes a parameter named t, which is a turtle. It
should use the turtle to draw a square.
Write a function call that passes bob as an argument to square, and then run the
program again.
2. Add another parameter, named length, to square. Modify the body so length of the
sides is length, and then modify the function call to provide a second argument. Run
the program again. Test your program with a range of values for length.
以下是我的作品:

import turtle
bob = turtle.Turtle()
print(bob)

def square(t, length):
    for i in range(4):
        bob.fd(t, length)
        bob.lt(t)

square(bob, 200)

turtle.mainloop()
以下是回溯:

Traceback (most recent call last):
  File "/Users/ivan/Documents/Python/thinkpython/square.py", line 10, in <module>
    square(bob, 200)
  File "/Users/ivan/Documents/Python/thinkpython/square.py", line 7, in square
    bob.fd(t, length)
TypeError: forward() takes 2 positional arguments but 3 were given
回溯(最近一次呼叫最后一次):
文件“/Users/ivan/Documents/Python/thinkpython/square.py”,第10行,在
广场(鲍勃,200)
文件“/Users/ivan/Documents/Python/thinkpython/square.py”,第7行,正方形
bob.fd(t,长度)
TypeError:forward()接受2个位置参数,但给出了3个

在回溯中我不理解的部分是,我只看到给bob.fd()的两个参数,但它说它收到了三个。有人能解释这种情况吗?

因为
bob
Turtle
类的一个实例化,
fd
是一个类函数,调用函数时传递一个隐式的
self
。如果您查看
Turtle
类中
fd
的定义,您会看到类似
def fd(self,distance)
的内容。调用类函数时,
bob.fd(t,length)
会隐式传递带有类实例化的
self
参数,然后传递另外两个参数
(t,length)
,总共3个参数。

fd
只接受一个参数
距离

.fd(距离)参数:
距离–一个数字(整数或浮点) 将乌龟向前移动指定距离,移动方向为乌龟前进的方向

  • 在您的情况下,您应该只使用您的turtle实例
    bob
    并调用
    fd
    ,其中包含一个参数,如
    t.fd(length)
  • 此外,您的turtle left turn函数接受整数或浮点,而不是turtle实例。因此,如果你想让海龟转90度,它应该像
    t.lt(90)
  • 您的问题要求您传入一只海龟作为参数
    t
    。这就是你的海龟的例子。这就是为什么我们不调用
    bob.fd()
    bob.lt
    而是调用
    t.fd()
    t.lt()

  • 上面的代码应该让海龟画一个200乘200的正方形。
    希望这有帮助。如果您仍然不明白,请留下评论,我会更详细地解释。

    试试
    bob.fd(长度)
    这很有效!非常感谢。太好了,我会把它作为答案加上一些解释。你的代码中还有一些错误,我也会在回答中解释。欢迎来到stackOverflow,谢谢!我是一名医科学生,决定进入编程领域,我正在自学,所以这对我来说都是全新的。看到这样一个乐于助人的社区真是太好了!谢谢你的解释。当我继续阅读时,我会记住这一点!我刚刚做了编辑,一切都很顺利!然而,问题2要求我们向square添加另一个参数,因此该函数应该有两个参数。我还不了解这是如何工作的。这个问题还要求我们修改函数调用以提供第二个参数,因此我们应该在square()中看到两个参数,对吗?哈哈,当你发布评论时,我正在编辑帖子。看看这是否有意义谢谢你的修改!因此,当我们调用函数平方(bob,200)时,变量bob正在替换变量t,并在体内替换,对吗?是的!你说对了!没错,我的朋友(๑❛ᴗ❛๑)多么美丽啊!
    import turtle
    bob = turtle.Turtle()
    print(bob)
    
    def square(t, length):
        for i in range(4):
            t.fd(length)
            t.lt(90)
    
    square(bob, 200)
    
    turtle.mainloop()