Dispatcher inside a class












1















I have this block of code:



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()


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



I am instantiating as:



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)


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?



I'm new regarding classes and objects, but I guess this is a way of handling things is a 'Dispatcher'. Am I right?










share|improve this question

























  • How are you instantiating Model? InputLayer is not a method as you say, but it is callable because of its __init__ method. callable(InputLayer) returns True.

    – JacobIRR
    Nov 28 '18 at 0:42











  • I am just doing a = Model(). I don't quite understand your answer, but are you saying that I can call the class InputLayer as a method because of the __init__ method ? I didn't know classes could be methods, can you point me to some documentation on this? Thanks!

    – Bruno Murino
    Nov 28 '18 at 1:00











  • You can’t do ‘Model()’ since it is missing 1 required positional argument (architecture). It is the init method that makes the class callable. I’m curious where you were reading about this dispatcher pattern. It may help to make your question a bit more specific.

    – JacobIRR
    Nov 28 '18 at 1:08











  • Oh sorry, I edited my question now. I just found a piece of code that was using that and discovered the name of this technique through another stack overflow question.

    – Bruno Murino
    Nov 28 '18 at 1:27











  • You need to put the self. before layer_type_map because it's a class attribute (that will be shared by all instance of the class). To reference them within a method of a class you can use either self. or the class name, i.e. Model.. The latter will also work outside methods of the class if desired (but that might not be a good thing to do because it's a bit like using a global variable depending on exactly why you're doing it).

    – martineau
    Nov 28 '18 at 1:34


















1















I have this block of code:



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()


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



I am instantiating as:



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)


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?



I'm new regarding classes and objects, but I guess this is a way of handling things is a 'Dispatcher'. Am I right?










share|improve this question

























  • How are you instantiating Model? InputLayer is not a method as you say, but it is callable because of its __init__ method. callable(InputLayer) returns True.

    – JacobIRR
    Nov 28 '18 at 0:42











  • I am just doing a = Model(). I don't quite understand your answer, but are you saying that I can call the class InputLayer as a method because of the __init__ method ? I didn't know classes could be methods, can you point me to some documentation on this? Thanks!

    – Bruno Murino
    Nov 28 '18 at 1:00











  • You can’t do ‘Model()’ since it is missing 1 required positional argument (architecture). It is the init method that makes the class callable. I’m curious where you were reading about this dispatcher pattern. It may help to make your question a bit more specific.

    – JacobIRR
    Nov 28 '18 at 1:08











  • Oh sorry, I edited my question now. I just found a piece of code that was using that and discovered the name of this technique through another stack overflow question.

    – Bruno Murino
    Nov 28 '18 at 1:27











  • You need to put the self. before layer_type_map because it's a class attribute (that will be shared by all instance of the class). To reference them within a method of a class you can use either self. or the class name, i.e. Model.. The latter will also work outside methods of the class if desired (but that might not be a good thing to do because it's a bit like using a global variable depending on exactly why you're doing it).

    – martineau
    Nov 28 '18 at 1:34
















1












1








1








I have this block of code:



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()


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



I am instantiating as:



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)


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?



I'm new regarding classes and objects, but I guess this is a way of handling things is a 'Dispatcher'. Am I right?










share|improve this question
















I have this block of code:



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()


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



I am instantiating as:



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)


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?



I'm new regarding classes and objects, but I guess this is a way of handling things is a 'Dispatcher'. Am I right?







python dispatcher






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 28 '18 at 1:30









martineau

68.9k1091186




68.9k1091186










asked Nov 28 '18 at 0:28









Bruno MurinoBruno Murino

155




155













  • How are you instantiating Model? InputLayer is not a method as you say, but it is callable because of its __init__ method. callable(InputLayer) returns True.

    – JacobIRR
    Nov 28 '18 at 0:42











  • I am just doing a = Model(). I don't quite understand your answer, but are you saying that I can call the class InputLayer as a method because of the __init__ method ? I didn't know classes could be methods, can you point me to some documentation on this? Thanks!

    – Bruno Murino
    Nov 28 '18 at 1:00











  • You can’t do ‘Model()’ since it is missing 1 required positional argument (architecture). It is the init method that makes the class callable. I’m curious where you were reading about this dispatcher pattern. It may help to make your question a bit more specific.

    – JacobIRR
    Nov 28 '18 at 1:08











  • Oh sorry, I edited my question now. I just found a piece of code that was using that and discovered the name of this technique through another stack overflow question.

    – Bruno Murino
    Nov 28 '18 at 1:27











  • You need to put the self. before layer_type_map because it's a class attribute (that will be shared by all instance of the class). To reference them within a method of a class you can use either self. or the class name, i.e. Model.. The latter will also work outside methods of the class if desired (but that might not be a good thing to do because it's a bit like using a global variable depending on exactly why you're doing it).

    – martineau
    Nov 28 '18 at 1:34





















  • How are you instantiating Model? InputLayer is not a method as you say, but it is callable because of its __init__ method. callable(InputLayer) returns True.

    – JacobIRR
    Nov 28 '18 at 0:42











  • I am just doing a = Model(). I don't quite understand your answer, but are you saying that I can call the class InputLayer as a method because of the __init__ method ? I didn't know classes could be methods, can you point me to some documentation on this? Thanks!

    – Bruno Murino
    Nov 28 '18 at 1:00











  • You can’t do ‘Model()’ since it is missing 1 required positional argument (architecture). It is the init method that makes the class callable. I’m curious where you were reading about this dispatcher pattern. It may help to make your question a bit more specific.

    – JacobIRR
    Nov 28 '18 at 1:08











  • Oh sorry, I edited my question now. I just found a piece of code that was using that and discovered the name of this technique through another stack overflow question.

    – Bruno Murino
    Nov 28 '18 at 1:27











  • You need to put the self. before layer_type_map because it's a class attribute (that will be shared by all instance of the class). To reference them within a method of a class you can use either self. or the class name, i.e. Model.. The latter will also work outside methods of the class if desired (but that might not be a good thing to do because it's a bit like using a global variable depending on exactly why you're doing it).

    – martineau
    Nov 28 '18 at 1:34



















How are you instantiating Model? InputLayer is not a method as you say, but it is callable because of its __init__ method. callable(InputLayer) returns True.

– JacobIRR
Nov 28 '18 at 0:42





How are you instantiating Model? InputLayer is not a method as you say, but it is callable because of its __init__ method. callable(InputLayer) returns True.

– JacobIRR
Nov 28 '18 at 0:42













I am just doing a = Model(). I don't quite understand your answer, but are you saying that I can call the class InputLayer as a method because of the __init__ method ? I didn't know classes could be methods, can you point me to some documentation on this? Thanks!

– Bruno Murino
Nov 28 '18 at 1:00





I am just doing a = Model(). I don't quite understand your answer, but are you saying that I can call the class InputLayer as a method because of the __init__ method ? I didn't know classes could be methods, can you point me to some documentation on this? Thanks!

– Bruno Murino
Nov 28 '18 at 1:00













You can’t do ‘Model()’ since it is missing 1 required positional argument (architecture). It is the init method that makes the class callable. I’m curious where you were reading about this dispatcher pattern. It may help to make your question a bit more specific.

– JacobIRR
Nov 28 '18 at 1:08





You can’t do ‘Model()’ since it is missing 1 required positional argument (architecture). It is the init method that makes the class callable. I’m curious where you were reading about this dispatcher pattern. It may help to make your question a bit more specific.

– JacobIRR
Nov 28 '18 at 1:08













Oh sorry, I edited my question now. I just found a piece of code that was using that and discovered the name of this technique through another stack overflow question.

– Bruno Murino
Nov 28 '18 at 1:27





Oh sorry, I edited my question now. I just found a piece of code that was using that and discovered the name of this technique through another stack overflow question.

– Bruno Murino
Nov 28 '18 at 1:27













You need to put the self. before layer_type_map because it's a class attribute (that will be shared by all instance of the class). To reference them within a method of a class you can use either self. or the class name, i.e. Model.. The latter will also work outside methods of the class if desired (but that might not be a good thing to do because it's a bit like using a global variable depending on exactly why you're doing it).

– martineau
Nov 28 '18 at 1:34







You need to put the self. before layer_type_map because it's a class attribute (that will be shared by all instance of the class). To reference them within a method of a class you can use either self. or the class name, i.e. Model.. The latter will also work outside methods of the class if desired (but that might not be a good thing to do because it's a bit like using a global variable depending on exactly why you're doing it).

– martineau
Nov 28 '18 at 1:34














2 Answers
2






active

oldest

votes


















0















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




Because layer_type_map is an attribute of Model, you need to refer to it whenever you want to access, by specify it with an instance of Model, by using self




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 is not a method of Model, but it is set in



layer_type_map = {
'input_layer': InputLayer
}


Since in the penultimate line, you've called self.layer_type_map[list(layer.keys())[0], you get the layer_type_map['input_layer']'s value, which is class InputLayer. Then you instantiate it by calling layer_class()



That is why your code work :D I haven't tried it yet but that is my brief explanation. Hope this help






share|improve this answer































    0














    You need to use self in your code because layer_type_map is a class variable. The rest of the code is just confusing you, I think. You can demonstrate the use of self in this context with a much simpler example:



    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()


    The self in your code is being used to look up self.layer_type_map, which is a dictionary. The indexing that gets done to the dictionary (to eventually get InputLayer) has nothing to do with the variable lookup, which happens first. The InputLayer class was looked up (in the global namespace) when the class was defined, and a reference to it was put into the dictionary.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53510322%2fdispatcher-inside-a-class%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0















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




      Because layer_type_map is an attribute of Model, you need to refer to it whenever you want to access, by specify it with an instance of Model, by using self




      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 is not a method of Model, but it is set in



      layer_type_map = {
      'input_layer': InputLayer
      }


      Since in the penultimate line, you've called self.layer_type_map[list(layer.keys())[0], you get the layer_type_map['input_layer']'s value, which is class InputLayer. Then you instantiate it by calling layer_class()



      That is why your code work :D I haven't tried it yet but that is my brief explanation. Hope this help






      share|improve this answer




























        0















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




        Because layer_type_map is an attribute of Model, you need to refer to it whenever you want to access, by specify it with an instance of Model, by using self




        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 is not a method of Model, but it is set in



        layer_type_map = {
        'input_layer': InputLayer
        }


        Since in the penultimate line, you've called self.layer_type_map[list(layer.keys())[0], you get the layer_type_map['input_layer']'s value, which is class InputLayer. Then you instantiate it by calling layer_class()



        That is why your code work :D I haven't tried it yet but that is my brief explanation. Hope this help






        share|improve this answer


























          0












          0








          0








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




          Because layer_type_map is an attribute of Model, you need to refer to it whenever you want to access, by specify it with an instance of Model, by using self




          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 is not a method of Model, but it is set in



          layer_type_map = {
          'input_layer': InputLayer
          }


          Since in the penultimate line, you've called self.layer_type_map[list(layer.keys())[0], you get the layer_type_map['input_layer']'s value, which is class InputLayer. Then you instantiate it by calling layer_class()



          That is why your code work :D I haven't tried it yet but that is my brief explanation. Hope this help






          share|improve this answer














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




          Because layer_type_map is an attribute of Model, you need to refer to it whenever you want to access, by specify it with an instance of Model, by using self




          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 is not a method of Model, but it is set in



          layer_type_map = {
          'input_layer': InputLayer
          }


          Since in the penultimate line, you've called self.layer_type_map[list(layer.keys())[0], you get the layer_type_map['input_layer']'s value, which is class InputLayer. Then you instantiate it by calling layer_class()



          That is why your code work :D I haven't tried it yet but that is my brief explanation. Hope this help







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 28 '18 at 1:41









          enamoriaenamoria

          634622




          634622

























              0














              You need to use self in your code because layer_type_map is a class variable. The rest of the code is just confusing you, I think. You can demonstrate the use of self in this context with a much simpler example:



              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()


              The self in your code is being used to look up self.layer_type_map, which is a dictionary. The indexing that gets done to the dictionary (to eventually get InputLayer) has nothing to do with the variable lookup, which happens first. The InputLayer class was looked up (in the global namespace) when the class was defined, and a reference to it was put into the dictionary.






              share|improve this answer




























                0














                You need to use self in your code because layer_type_map is a class variable. The rest of the code is just confusing you, I think. You can demonstrate the use of self in this context with a much simpler example:



                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()


                The self in your code is being used to look up self.layer_type_map, which is a dictionary. The indexing that gets done to the dictionary (to eventually get InputLayer) has nothing to do with the variable lookup, which happens first. The InputLayer class was looked up (in the global namespace) when the class was defined, and a reference to it was put into the dictionary.






                share|improve this answer


























                  0












                  0








                  0







                  You need to use self in your code because layer_type_map is a class variable. The rest of the code is just confusing you, I think. You can demonstrate the use of self in this context with a much simpler example:



                  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()


                  The self in your code is being used to look up self.layer_type_map, which is a dictionary. The indexing that gets done to the dictionary (to eventually get InputLayer) has nothing to do with the variable lookup, which happens first. The InputLayer class was looked up (in the global namespace) when the class was defined, and a reference to it was put into the dictionary.






                  share|improve this answer













                  You need to use self in your code because layer_type_map is a class variable. The rest of the code is just confusing you, I think. You can demonstrate the use of self in this context with a much simpler example:



                  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()


                  The self in your code is being used to look up self.layer_type_map, which is a dictionary. The indexing that gets done to the dictionary (to eventually get InputLayer) has nothing to do with the variable lookup, which happens first. The InputLayer class was looked up (in the global namespace) when the class was defined, and a reference to it was put into the dictionary.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 28 '18 at 1:41









                  BlckknghtBlckknght

                  64.1k557106




                  64.1k557106






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53510322%2fdispatcher-inside-a-class%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                      Calculate evaluation metrics using cross_val_predict sklearn

                      Insert data from modal to MySQL (multiple modal on website)