dea*_*ous 4 python error-handling attributes
我尝试在此站点上运行使用 Turtle 库的代码,如下所示,
import turtle
import random
def main():
tList = []
head = 0
numTurtles = 10
wn = turtle.Screen()
wn.setup(500,500)
for i in range(numTurtles):
nt = turtle.Turtle() # Make a new turtle, initialize values
nt.setheading(head)
nt.pensize(2)
nt.color(random.randrange(256),random.randrange(256),random.randrange(256))
nt.speed(10)
wn.tracer(30,0)
tList.append(nt) # Add the new turtle to the list
head = head + 360/numTurtles
for i in range(100):
moveTurtles(tList,15,i)
w = tList[0]
w.up()
w.goto(0,40)
w.write("How to Think Like a ",True,"center","40pt Bold")
w.goto(0,-35)
w.write("Computer Scientist",True,"center","40pt Bold")
def moveTurtles(turtleList,dist,angle):
for turtle in turtleList: # Make every turtle on the list do the same actions.
turtle.forward(dist)
turtle.right(angle)
main()
Run Code Online (Sandbox Code Playgroud)
在我自己的 Python 编辑器中,我收到了这个错误:
turtle.TurtleGraphicsError:颜色序列错误:(236、197、141)
然后,基于另一个站点上的这个答案,我在“nt.color(......)”之前添加了这一行
nt.colormode(255)
现在它向我展示了这个错误
AttributeError: 'Turtle' 对象没有属性 'colormode'
好的,所以我检查了我的 Python 库并查看了 Turtle.py 的内容。colormode() 属性肯定存在。是什么使代码能够在原始站点上运行但不能在我自己的计算机上运行?
问题是您的Turtle对象 ( nt) 没有colormode方法。不过,在turtle 模块中也有一个。
所以你只需要:
turtle.colormode(255)
Run Code Online (Sandbox Code Playgroud)
代替
nt.colormode(255)
Run Code Online (Sandbox Code Playgroud)
编辑:为了尝试在评论中澄清您的问题,假设我创建了一个名为 的模块test.py,其中包含一个函数和一个类“Test”:
# module test.py
def colormode():
print("called colormode() function in module test")
class Test
def __init__(self):
pass
Run Code Online (Sandbox Code Playgroud)
现在,我使用这个模块:
import test
nt = test.Test() # created an instance of this class (like `turtle.Turtle()`)
# nt.colormode() # won't work, since `colormode` isn't a method in the `Test` class
test.colormode() # works, since `colormode` is defined directly in the `test` module
Run Code Online (Sandbox Code Playgroud)