What's the difference between a method and a function?

前端 未结 30 4275
粉色の甜心
粉色の甜心 2020-11-21 05:08

Can someone provide a simple explanation of methods vs. functions in OOP context?

30条回答
  •  滥情空心
    2020-11-21 05:42

    Since you mentioned Python, the following might be a useful illustration of the relationship between methods and objects in most modern object-oriented languages. In a nutshell what they call a "method" is just a function that gets passed an extra argument (as other answers have pointed out), but Python makes that more explicit than most languages.

    # perfectly normal function
    def hello(greetee):
      print "Hello", greetee
    
    # generalise a bit (still a function though)
    def greet(greeting, greetee):
      print greeting, greetee
    
    # hide the greeting behind a layer of abstraction (still a function!)
    def greet_with_greeter(greeter, greetee):
      print greeter.greeting, greetee
    
    # very simple class we can pass to greet_with_greeter
    class Greeter(object):
      def __init__(self, greeting):
        self.greeting = greeting
    
      # while we're at it, here's a method that uses self.greeting...
      def greet(self, greetee):
        print self.greeting, greetee
    
    # save an object of class Greeter for later
    hello_greeter = Greeter("Hello")
    
    # now all of the following print the same message
    hello("World")
    greet("Hello", "World")
    greet_with_greeter(hello_greeter, "World")
    hello_greeter.greet("World")
    

    Now compare the function greet_with_greeter and the method greet: the only difference is the name of the first parameter (in the function I called it "greeter", in the method I called it "self"). So I can use the greet method in exactly the same way as I use the greet_with_greeter function (using the "dot" syntax to get at it, since I defined it inside a class):

    Greeter.greet(hello_greeter, "World")
    

    So I've effectively turned a method into a function. Can I turn a function into a method? Well, as Python lets you mess with classes after they're defined, let's try:

    Greeter.greet2 = greet_with_greeter
    hello_greeter.greet2("World")
    

    Yes, the function greet_with_greeter is now also known as the method greet2. This shows the only real difference between a method and a function: when you call a method "on" an object by calling object.method(args), the language magically turns it into method(object, args).

    (OO purists might argue a method is something different from a function, and if you get into advanced Python or Ruby - or Smalltalk! - you will start to see their point. Also some languages give methods special access to bits of an object. But the main conceptual difference is still the hidden extra parameter.)

提交回复
热议问题