尝试从self.density
的{{1}}方法中select_object
方法中访问populate_grid
中的实例变量class Map
时,我得到AttributeError: 'Map' object has no attribute 'density'
。
但是,仅从self.density
访问select_object
就可以了。
有人可以解释一下我没看到的内容吗?
# Handles player and scene locations
from random import randint, choice
class Map(object):
def __init__(self, size, objects, density=0.05):
self.size = size
self.objects = objects
self.grid = self.populate_grid(size)
self.density = density
def populate_grid(self, size):
grid = {}
for i in range(size):
y = 0
for j in range(size):
grid[C(i, y)] = self.select_object()
y += 1
return grid
def select_object(self):
if randint(0, 100) < (self.density*100):
print('yes')
return choice(self.objects)
else:
return 0
random_objects = ['A', 'B', 'C', 'D', 'E']
s = Map(4, random_objects, 0.5)
s.select_object()
此处提供完整代码:http://pastebin.com/TxLMSbH0
答案 0 :(得分:5)
问题是您在初始化self.density之前调用了self.grid = self.populate_grid(size)
。因此,当populate_grid执行时,self.density
未设置。
解决方案是将self.density = density
移到该呼叫之上。