类内的调度程序

2024-04-24 13:11:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码:

class InputLayer():
    def __init__(self):
        print('Test')

class Model():

    layer_type_map = {
        'input_layer': InputLayer
    }

    def __init__(self, architecture):

        for layer in architecture:

            layer_class = self.layer_type_map[list(layer.keys())[0]]
            layer_class()

我的问题是:在倒数第二行,为什么我要放self.?你知道吗

我的例子是:

layer0 = {'input_layer': {'input_shape': input_shape}}
layer1 = {'fc_layer': {'num_nodes' : 5}}
layer2 = {'output_layer': {'num_outputs' : 10}}

architecture = [layer0, layer1, layer2]

mynet = Model(architecture)

如果我正确使用代码,layer_type_map[list(layer.keys())[0]]的值是InputLayer,但是InputLayer不是Model类的方法。为什么这样做?你知道吗

对于类和对象我是新手,但我想这是一种处理事物的方法,它是一个“调度器”。我说得对吗?你知道吗


Tags: 代码selflayermapinputmodelinitdef
2条回答

My question is: in that penultimate line, why I need to put self.?

因为layer_type_mapModel的一个属性,所以您需要在需要访问它时引用它,方法是使用self指定一个Model的实例

If I use the code correctly, the value of layer_type_map[list(layer.keys())[0]] is InputLayer, but InputLayer is not a method of the Model class. Why does this work?

InputLayer不是Model的方法,但它是在

layer_type_map = {
    'input_layer': InputLayer
}

因为在倒数第二行中,调用了self.layer_type_map[list(layer.keys())[0],得到了layer_type_map['input_layer']的值,即class InputLayer。然后通过调用layer_class()来实例化它

这就是为什么你的代码工作:D我还没有尝试过,但这是我的简短解释。希望这有帮助

您需要在代码中使用self,因为layer_type_map是一个类变量。我想剩下的代码只是把你弄糊涂了。您可以用一个更简单的例子来演示self在这种情况下的用法:

class Foo:
    class_var = "a class variable"

    def method(self):
        print("accessing class_var via self works", self.class_var)
        print("so does accessing class_var via Foo", Foo.class_var)
        print("accessing class_var directly doesn't work", class_var) # raises an exception

instance = Foo()
instance.method()

代码中的self用于查找self.layer_type_map,这是一个字典。对字典所做的索引(最终得到InputLayer)与变量查找无关,变量查找首先发生。在定义InputLayer类时,会在全局命名空间中查找该类,并将对该类的引用放入字典中。你知道吗

相关问题 更多 >