Storing function name in dictionary and returning function name with parameters












2














def add(op1,op2):
return op1 + op2

def sub(op1,op2):
return op1 - op2

def mul(op1,op2):
return op1 * op2

def div(op1,op2):
return op1 / op2



def evaluate(op1,operator,op2):
ops = {'+':add,'-':sub,'*':mul,'/':div}
return ops[operator](op1,op2)

print(evaluate(1,'/',2))

>>> 0.5


I was messing around with dictionaries and I got this idea of storing a function name as a value and then returning that function name with parameters. I was surprised to see it actually worked. I don't know how this is possible and what's going on behind the scenes so can someone explain to me what exactly is happening in this piece of code in detail?










share|improve this question


















  • 1




    Functions are objects. They can be assigned, stored, and passed as parameters, just like any other object.
    – John Gordon
    Nov 22 at 23:57
















2














def add(op1,op2):
return op1 + op2

def sub(op1,op2):
return op1 - op2

def mul(op1,op2):
return op1 * op2

def div(op1,op2):
return op1 / op2



def evaluate(op1,operator,op2):
ops = {'+':add,'-':sub,'*':mul,'/':div}
return ops[operator](op1,op2)

print(evaluate(1,'/',2))

>>> 0.5


I was messing around with dictionaries and I got this idea of storing a function name as a value and then returning that function name with parameters. I was surprised to see it actually worked. I don't know how this is possible and what's going on behind the scenes so can someone explain to me what exactly is happening in this piece of code in detail?










share|improve this question


















  • 1




    Functions are objects. They can be assigned, stored, and passed as parameters, just like any other object.
    – John Gordon
    Nov 22 at 23:57














2












2








2







def add(op1,op2):
return op1 + op2

def sub(op1,op2):
return op1 - op2

def mul(op1,op2):
return op1 * op2

def div(op1,op2):
return op1 / op2



def evaluate(op1,operator,op2):
ops = {'+':add,'-':sub,'*':mul,'/':div}
return ops[operator](op1,op2)

print(evaluate(1,'/',2))

>>> 0.5


I was messing around with dictionaries and I got this idea of storing a function name as a value and then returning that function name with parameters. I was surprised to see it actually worked. I don't know how this is possible and what's going on behind the scenes so can someone explain to me what exactly is happening in this piece of code in detail?










share|improve this question













def add(op1,op2):
return op1 + op2

def sub(op1,op2):
return op1 - op2

def mul(op1,op2):
return op1 * op2

def div(op1,op2):
return op1 / op2



def evaluate(op1,operator,op2):
ops = {'+':add,'-':sub,'*':mul,'/':div}
return ops[operator](op1,op2)

print(evaluate(1,'/',2))

>>> 0.5


I was messing around with dictionaries and I got this idea of storing a function name as a value and then returning that function name with parameters. I was surprised to see it actually worked. I don't know how this is possible and what's going on behind the scenes so can someone explain to me what exactly is happening in this piece of code in detail?







python python-3.x






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 at 23:51









BrowserM

374




374








  • 1




    Functions are objects. They can be assigned, stored, and passed as parameters, just like any other object.
    – John Gordon
    Nov 22 at 23:57














  • 1




    Functions are objects. They can be assigned, stored, and passed as parameters, just like any other object.
    – John Gordon
    Nov 22 at 23:57








1




1




Functions are objects. They can be assigned, stored, and passed as parameters, just like any other object.
– John Gordon
Nov 22 at 23:57




Functions are objects. They can be assigned, stored, and passed as parameters, just like any other object.
– John Gordon
Nov 22 at 23:57












2 Answers
2






active

oldest

votes


















1














If you're experienced in C or C++, then you'll be aware of the idea of "function pointers" - you take the memory address of a function, put it in a variable, and then later execute "the function at that memory address". It's pretty much the same in python.



Essentially, python treats a function as its own type of object:



>>> def x():
... print("Hello World")
...
>>> type(x)
<class 'function'>


A function can be called with the parentheses operators, obviously. However, since a function is also an object, you can put that function inside of a variable:



>>> y = x
>>> y()
Hello World


What you're doing with the dict is making key-value pairs: "+" corresponds to the object add; and since add is a function, it can be called.






share|improve this answer





























    1














    To Explain:




    • The first four functions are making operator functions


    • Then in the evaluate function, it creates a dictionary, with the signs as key, and the functions as values


    • Then, get the operator argument, which is one of the signs, so get the value of the key:value pair when the key is that sign, then you just call that value since it's a function



    Note that there's a better code, actually operator module contains the first four functions already.



    The code for that:



    from operator import add,sub,mul,truediv
    def evaluate(op1,operator,op2):
    ops = {'+':add,'-':sub,'*':mul,'/':truediv}
    return ops[operator](op1,op2)

    print(evaluate(1,'/',2))


    Output:



    0.5





    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%2f53439195%2fstoring-function-name-in-dictionary-and-returning-function-name-with-parameters%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









      1














      If you're experienced in C or C++, then you'll be aware of the idea of "function pointers" - you take the memory address of a function, put it in a variable, and then later execute "the function at that memory address". It's pretty much the same in python.



      Essentially, python treats a function as its own type of object:



      >>> def x():
      ... print("Hello World")
      ...
      >>> type(x)
      <class 'function'>


      A function can be called with the parentheses operators, obviously. However, since a function is also an object, you can put that function inside of a variable:



      >>> y = x
      >>> y()
      Hello World


      What you're doing with the dict is making key-value pairs: "+" corresponds to the object add; and since add is a function, it can be called.






      share|improve this answer


























        1














        If you're experienced in C or C++, then you'll be aware of the idea of "function pointers" - you take the memory address of a function, put it in a variable, and then later execute "the function at that memory address". It's pretty much the same in python.



        Essentially, python treats a function as its own type of object:



        >>> def x():
        ... print("Hello World")
        ...
        >>> type(x)
        <class 'function'>


        A function can be called with the parentheses operators, obviously. However, since a function is also an object, you can put that function inside of a variable:



        >>> y = x
        >>> y()
        Hello World


        What you're doing with the dict is making key-value pairs: "+" corresponds to the object add; and since add is a function, it can be called.






        share|improve this answer
























          1












          1








          1






          If you're experienced in C or C++, then you'll be aware of the idea of "function pointers" - you take the memory address of a function, put it in a variable, and then later execute "the function at that memory address". It's pretty much the same in python.



          Essentially, python treats a function as its own type of object:



          >>> def x():
          ... print("Hello World")
          ...
          >>> type(x)
          <class 'function'>


          A function can be called with the parentheses operators, obviously. However, since a function is also an object, you can put that function inside of a variable:



          >>> y = x
          >>> y()
          Hello World


          What you're doing with the dict is making key-value pairs: "+" corresponds to the object add; and since add is a function, it can be called.






          share|improve this answer












          If you're experienced in C or C++, then you'll be aware of the idea of "function pointers" - you take the memory address of a function, put it in a variable, and then later execute "the function at that memory address". It's pretty much the same in python.



          Essentially, python treats a function as its own type of object:



          >>> def x():
          ... print("Hello World")
          ...
          >>> type(x)
          <class 'function'>


          A function can be called with the parentheses operators, obviously. However, since a function is also an object, you can put that function inside of a variable:



          >>> y = x
          >>> y()
          Hello World


          What you're doing with the dict is making key-value pairs: "+" corresponds to the object add; and since add is a function, it can be called.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 23 at 0:00









          Green Cloak Guy

          2,4481720




          2,4481720

























              1














              To Explain:




              • The first four functions are making operator functions


              • Then in the evaluate function, it creates a dictionary, with the signs as key, and the functions as values


              • Then, get the operator argument, which is one of the signs, so get the value of the key:value pair when the key is that sign, then you just call that value since it's a function



              Note that there's a better code, actually operator module contains the first four functions already.



              The code for that:



              from operator import add,sub,mul,truediv
              def evaluate(op1,operator,op2):
              ops = {'+':add,'-':sub,'*':mul,'/':truediv}
              return ops[operator](op1,op2)

              print(evaluate(1,'/',2))


              Output:



              0.5





              share|improve this answer




























                1














                To Explain:




                • The first four functions are making operator functions


                • Then in the evaluate function, it creates a dictionary, with the signs as key, and the functions as values


                • Then, get the operator argument, which is one of the signs, so get the value of the key:value pair when the key is that sign, then you just call that value since it's a function



                Note that there's a better code, actually operator module contains the first four functions already.



                The code for that:



                from operator import add,sub,mul,truediv
                def evaluate(op1,operator,op2):
                ops = {'+':add,'-':sub,'*':mul,'/':truediv}
                return ops[operator](op1,op2)

                print(evaluate(1,'/',2))


                Output:



                0.5





                share|improve this answer


























                  1












                  1








                  1






                  To Explain:




                  • The first four functions are making operator functions


                  • Then in the evaluate function, it creates a dictionary, with the signs as key, and the functions as values


                  • Then, get the operator argument, which is one of the signs, so get the value of the key:value pair when the key is that sign, then you just call that value since it's a function



                  Note that there's a better code, actually operator module contains the first four functions already.



                  The code for that:



                  from operator import add,sub,mul,truediv
                  def evaluate(op1,operator,op2):
                  ops = {'+':add,'-':sub,'*':mul,'/':truediv}
                  return ops[operator](op1,op2)

                  print(evaluate(1,'/',2))


                  Output:



                  0.5





                  share|improve this answer














                  To Explain:




                  • The first four functions are making operator functions


                  • Then in the evaluate function, it creates a dictionary, with the signs as key, and the functions as values


                  • Then, get the operator argument, which is one of the signs, so get the value of the key:value pair when the key is that sign, then you just call that value since it's a function



                  Note that there's a better code, actually operator module contains the first four functions already.



                  The code for that:



                  from operator import add,sub,mul,truediv
                  def evaluate(op1,operator,op2):
                  ops = {'+':add,'-':sub,'*':mul,'/':truediv}
                  return ops[operator](op1,op2)

                  print(evaluate(1,'/',2))


                  Output:



                  0.5






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 23 at 0:01

























                  answered Nov 22 at 23:55









                  U9-Forward

                  12k21136




                  12k21136






























                      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.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • 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%2f53439195%2fstoring-function-name-in-dictionary-and-returning-function-name-with-parameters%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

                      Contact image not getting when fetch all contact list from iPhone by CNContact

                      count number of partitions of a set with n elements into k subsets

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