Python:无法访问Class函数中的Instance Variable

时间:2015-11-09 07:45:28

标签: python class variables object

尝试从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

1 个答案:

答案 0 :(得分:5)

问题是您在初始化self.density之前调用了self.grid = self.populate_grid(size) 。因此,当populate_grid执行时,self.density未设置。

解决方案是将self.density = density移到该呼叫之上。