我有这个 Python 代码:
import math, random, sys
from swampy.TurtleWorld import *
world = TurtleWorld()
Rasmus = Turtle()
Rasmus.delay = 0.000002
class rule(object):
def __init__(self):
self.rule={} #we make an empty dictionary
def newrule(self,leftside,rightside):
self.rule[leftside]=rightside #we fill the dictionary
def expand (self,oldlist,depth):
if depth <= 0:
return oldlist
newlist=[] # we make an empty new list
for i in oldlist:
if i not in self.rule:
newlist.append(i)
else:
newlist.append(self.expand(self.rule[i],depth-1))
return newlist
class command(object):
def __init__(self, cmd, length):
self.cmd = cmd
self.length = length
def execute(self, turtle, length):
if self.cmd=='lt':
lt(turtle, int(self.length[0]))
if self.cmd=='rt':
rt(turtle, int(self.length[0]))
if self.cmd=='fd':
fd(turtle, length)
if self.cmd=='bk':
bk(turtle, length)
if self.cmd=='scale':
length = length*float(self.length[0])
class Fractal(object):
def __init__(self, rules, commands, start, length, depth):
self.rules = rules
self.commands = commands
self.start = start
self.length = length
self.depth = depth
def draw(self, oldlist):
for i in oldlist:
if type(i) == list:
self.draw(i)
else:
cmd = self.commands[i]
cmd.execute(Rasmus, self.length)
def read():
files = open('sierpinski2.fdl')
commands = {}
r = rule()
for line in files:
line = line.strip()
oldlist = line.split(' ')
if oldlist[0] == 'start':
start = oldlist[1:]
elif oldlist[0] == 'rule':
r.newrule(oldlist[1], oldlist[3:])
elif oldlist[0] == 'cmd':
cmd = command(oldlist[2], oldlist[3:])
commands[oldlist[1]] = cmd
elif oldlist[0] == 'length':
length = int(oldlist[1])
elif oldlist[0] == 'depth':
depth = int(oldlist[1])
return Fractal(start, r, commands, length, depth)
re = read()
print re.commands.keys()
length = re.rules.expand(re.start , re.depth)
re.draw(l)
wait_for_user()
它应该从 sierpinski.fdl 文件中提取信息,如下所示:
start F L F L F L
rule F -> F L F L F L F F
length 8
depth 5
cmd F fd
cmd L lt 120
我的问题是,当我运行它时,它给了我这个错误:
Traceback (most recent call last):
File "C:\Python27\PythonScripts\swampy-2.1.1\swampy\Projekt del 2.py", line 81, in <module>
print re.commands.keys()
AttributeError: 'rule' object has no attribute 'keys'
我知道问题在于:
re = read()
print re.commands.keys()
length = re.rules.expand(re.start , re.depth)
re.draw
部分代码,我启用程序的执行,但我似乎无法修复它。
我正在使用 python 2.7.5