为什么传递给函数的所有数据都是“显式传递”的?

Art*_*ani 4 methods function implicit argument-passing

数据“显式”传递给函数,而方法“隐式传递”给调用它的对象。

请您解释一下这两种传递数据的方式之间的区别吗?java 或 c# 中的示例会有所帮助。

Sim*_*ser 5

Java 和 Python 语言是说明这一点的好例子。在 Python 中,只要定义了类的方法,就会显式传递对象:

class Example(object):

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

在这里,对象self作为第一个参数显式传递。这意味着

e = Example()
e.method(3, 4)
Run Code Online (Sandbox Code Playgroud)

实际上与调用method(e, 3, 4)ifmethod是函数相同。

但是,在 Java 中没有明确提到第一个参数:

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
    } 
}
Run Code Online (Sandbox Code Playgroud)

在 Java 中,它将是:

Example e = Example();
e.method(3, 4);
Run Code Online (Sandbox Code Playgroud)

实例也e被传递给method,但this可以使用特殊变量来访问它。

当然,对于函数,每个参数都显式传递,因为每个参数都在函数定义和调用函数的位置中提及。如果我们定义

def func(a, b, c):
    print a, b, c
Run Code Online (Sandbox Code Playgroud)

然后我们可以调用它,func(1, 2, 3)这意味着所有参数都显式传递。