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

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

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

相关标签:
30条回答
  • 2020-11-21 05:39

    Difference Between Methods and Functions

    From reading this doc on Microsoft

    Members that contain executable code are collectively known as the function members of a class. The preceding section describes methods, which are the primary kind of function members. This section describes the other kinds of function members supported by C#: constructors, properties, indexers, events, operators, and finalizers.

    So methods are the subset of the functions. Every method is a function but not every function is a method, for example, a constructor can't be said as a method but it is a function.

    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2020-11-21 05:42

    IMHO people just wanted to invent new word for easier communication between programmers when they wanted to refer to functions inside objects.

    If you are saying methods you mean functions inside the class. If you are saying functions you mean simply functions outside the class.

    The truth is that both words are used to describe functions. Even if you used it wrongly nothing wrong happens. Both words describe well what you want to achieve in your code.

    Function is a code that has to play a role (a function) of doing something. Method is a method to resolve the problem.

    It does the same thing. It is the same thing. If you want to be super precise and go along with the convention you can call methods as the functions inside objects.

    0 讨论(0)
  • 2020-11-21 05:43

    Function or a method is a named callable piece of code which performs some operations and optionally returns a value.

    In C language the term function is used. Java & C# people would say it a method (and a function in this case is defined within a class/object).

    A C++ programmer might call it a function or sometimes method (depending on if they are writing procedural style c++ code or are doing object oriented way of C++, also a C/C++ only programmer would likely call it a function because term 'method' is less often used in C/C++ literature).

    You use a function by just calling it's name like,

    result = mySum(num1, num2);
    


    You would call a method by referencing its object first like,

    result = MyCalc.mySum(num1,num2);
    
    0 讨论(0)
  • 2020-11-21 05:43

    To a first order approximation, a method (in C++ style OO) is another word for a member function, that is a function that is part of a class.

    In languages like C/C++ you can have functions which are not members of a class; you don't call a function not associated with a class a method.

    0 讨论(0)
  • 2020-11-21 05:45

    Here is some explanation for method vs. function using JavaScript examples:

    test(20, 50); is function define and use to run some steps or return something back that can be stored/used somewhere.

    You can reuse code: Define the code once and use it many times.

    You can use the same code many times with different arguments, to produce different results.

    var x = myFunction(4, 3);   // Function is called, return value will end up in x
    
    function myFunction(a, b) {
        return a * b;          // Function returns the product of a and b
    }
    

    var test = something.test(); here test() can be a method of some object or custom defined a prototype for inbuilt objects, here is more explanation:

    JavaScript methods are the actions that can be performed on objects.

    A JavaScript method is a property containing a function definition.

    Built-in property/method for strings in javascript:

    var message = "Hello world!";
    var x = message.toUpperCase();
    //Output: HELLO WORLD!
    

    Custom example:

    function person(firstName, lastName, age, eyeColor) {
        this.firstName = firstName;  
        this.lastName = lastName;
        this.age = age;
        this.eyeColor = eyeColor;
        this.changeName = function (name) {
            this.lastName = name;
        };
    }
    
    something.changeName("SomeName"); //This will change 'something' objject's name to 'SomeName'
    

    You can define properties for String, Array, etc as well for example

    String.prototype.distance = function (char) {
        var index = this.indexOf(char);
    
        if (index === -1) {
            console.log(char + " does not appear in " + this);
        } else {
            console.log(char + " is " + (this.length - index) + " characters from the end of the string!");
        }
    };
    
    var something = "ThisIsSomeString"
    
    // now use distance like this, run and check console log
    
    something.distance("m");

    Some references: Javascript Object Method, Functions, More info on prototype

    0 讨论(0)
提交回复
热议问题