内部 class 可以检索顶部 class 的实例吗?

Can an inner class retrieve the instance of the top class?

我正在处理的程序使用嵌套 classes。顶部 class 名为 Brain,它有两个内部 class,NeuronAxon。内层classes需要能够修改topclass.

的实例变量

Brain 跟踪实例化了多少个神经元和轴突。 Neuron 保存有关其动作电位及其输出的信息。 Axon 确定如何将能量从一个神经元传递到另一个神经元。这样,每当我实例化一个神经元时,它就会保存在大脑的实例中。轴突也是如此。


到目前为止,这是我的代码:

class Brain(object):
    def __init__(self):
        self.neurons = []
        self.axons = []

    class Neuron(object):
        def __init__(self, pos, AP_Energy, AP_threshold):
            # General attributes
            self.outputs = {}
            self.Energy = 0
            self.x, self.y = pos[0], pos[1]

            # Action Potential attributes
            self.AP_Energy = AP_Energy
            self.AP_threshold = AP_threshold

            """Append self to instance
               of Brain in neurons"""

        def add(self, value): self.Energy += value
        def link(self, neuron, weight): self.outputs[neuron] = weight

        def act(self):
            for neuron in self.outputs.keys():
                """Append Axon(self, neuron) to
                   instance of Brain in axons"""

    class Axon(object):
        def __init__(self, n1, n2):
            # Neurons
            self.n1, self.n2 = n1, n2

            # Action Potential attributes
            self.wavelength = sqrt((5*n1.AP_Energy)/3)
            self.distance = sqrt((n2.x-n1.x)**2+(n2.y-n1.y)**2)

        def action_potential(self): # Bunch of math stuff

这个想法是你可以创建神经元而不必将大脑实例作为其参数之一。因此,如果我想用两个神经元创建 Brain 的实例,它应该显示为:

EntityA = Brain()
EntityA.Neuron((0, 1), 15, 24)
EntityA.Neuron((4, 2), 30, 41)

如果我需要从 EntityA 中的第一个神经元调用 add(),我应该能够将其称为 EntityA.neurons[0].add(value),因为在我创建神经元时它应该自动将自己附加到列表中。

我该怎么做,如果不可能,可以做些什么来得到类似的结果?


编辑:使用函数实例化 class Neuron 并将其保存到 Brain 实例中的列表似乎显而易见的答案。 问题出现在实例化classAxon的函数Neuron.act()中,并且必须将其保存到中的列表中与用于神经元的 Brain 相同的 个实例。之前的限制仍然适用。

class Brain(object):
    def __init__(self):
        self.neurons = []
        self.axons = []

    class Neuron(object):
        ...

    class Axon(object):
        ...

    def add_neuron(self, pos, AP_Energy, AP_threshold):
        self.neurons.append(Brain.Neuron(pos, AP_Energy, AP_threshold))


EntityA = Brain()
EntityA.add_neuron((0, 10), 15, 24)