Why is all the data passed to the function "explicitly passed"?

Data is passed to a function "explicitly", while a method is "implicitly passed" to the object on which it was called.

Could you please explain the difference between these two data transfer methods? An example in java or C # will help.

+3


source to share


2 answers


Java and Python are good examples to illustrate this. In Python, an object is passed explicitly whenever a class method is defined:

class Example(object):

    def method(self, a, b):
        print a, b
        # The variable self can be used to access the current object

      

Here, the object self

is passed explicitly as the first argument. It means that

e = Example()
e.method(3, 4)

      

is actually the same as calling method(e, 3, 4)

if it method

was a function.

However, in Java, the first argument is not explicitly mentioned:

public class Example {
    public void method(int a, int b) {
        System.out.println(a + "  " + b);
        // The variable this can be used to access the current object
    } 
}

      



In Java this would be:

Example e = Example();
e.method(3, 4);

      

An instance is e

also passed to method

, but a special variable this

can be used to access it.

Of course, for functions, each argument is passed explicitly, because each argument is referred to both in the function definition and in the function call. If we define

def func(a, b, c):
    print a, b, c

      

then we can call it with func(1, 2, 3)

, which means that all arguments are explicitly passed.

+4


source


In this context, a method can be thought of as a function that has access to the object to which it is bound. Any properties of this object can be accessed from the method, even if they do not appear in the function signature. You didn't specify the language, but let me give you a PHP example, as it's pretty common and easy to read even if you haven't used it.

Edit: languages ​​were added after I wrote this; maybe someone can translate this into one of these languages ​​if needed.



<?php
/* Explicit passing to a function */
function f($a, b)
{
    return $a + b;
} 

// f(1, 2) == 3

class C
{
    public $a, $b;

    /* $a and $b are not in the parameter list. They're accessed via the special $this variable that points to the current object. */
    public function m() 
    {
        return $this->a + $this->b;
    }

}

$o = new C();
$o->a = 1;
$o->b = 2;
//$o->m() == 3

      

+1


source







All Articles