方法和函数有什么区别?

发布于 2024-07-05 18:12:55 字数 69 浏览 6 评论 0 原文

有人可以提供 OOP 上下文中的方法函数的简单解释吗?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

时光礼记 2024-07-12 18:12:55

为我:
如果我同意,方法和函数的功能是相同的:

  • 函数可能返回一个值
  • 可能需要参数

就像任何代码一样,您可能有放入的对象,并且可能有一个作为结果出现的对象。 在此过程中,它们可能会改变对象的状态,但这不会改变它们对我来说的基本功能。

调用对象或其他代码的函数时可能存在定义差异。 但这难道不是一种语言上的差异,而这就是人们互换它们的原因吗? 提到的计算示例我会小心处理。 因为我雇用员工来进行计算:

new Employer().calculateSum( 8, 8 );

通过这样做,我可以信赖负责计算的雇主。 如果他想要更多的钱,我就释放他,让碳水化合物收集者处理未使用的员工的功能完成剩下的工作并招募一名新员工。

即使争论方法是对象函数而函数是未连接的计算也对我没有帮助。 函数描述符本身以及理想情况下函数的文档将告诉我它需要什么以及它可能返回什么。 其余的,比如操纵某个对象的状态,对我来说并不是真正透明的。 我确实希望函数和方法都能交付和操纵它们所声称的内容,而无需详细了解它们是如何做到的。
即使是纯计算函数也可能会更改控制台的状态或附加到日志文件。

for me:
the function of a method and a function is the same if I agree that:

  • a function may return a value
  • may expect parameters

Just like any piece of code you may have objects you put in and you may have an object that comes as a result. During doing that they might change the state of an object but that would not change their basic functioning for me.

There might be a definition differencing in calling functions of objects or other codes. But isn't that something for a verbal differenciations and that's why people interchange them? The mentions example of computation I would be careful with. because I hire employes to do my calculations:

new Employer().calculateSum( 8, 8 );

By doing it that way I can rely on an employer being responsible for calculations. If he wants more money I free him and let the carbage collector's function of disposing unused employees do the rest and get a new employee.

Even arguing that a method is an objects function and a function is unconnected computation will not help me. The function descriptor itself and ideally the function's documentation will tell me what it needs and what it may return. The rest, like manipulating some object's state is not really transparent to me. I do expect both functions and methods to deliver and manipulate what they claim to without needing to know in detail how they do it.
Even a pure computational function might change the console's state or append to a logfile.

伪心 2024-07-12 18:12:55

我们不要把本来应该非常简单的答案搞得太复杂。 方法和函数是同一个东西。 当函数在类外部时,您将其称为函数;当函数在类内部编写时,您将函数称为方法。

Let's not over complicate what should be a very simple answer. Methods and functions are the same thing. You call a function a function when it is outside of a class, and you call a function a method when it is written inside a class.

远昼 2024-07-12 18:12:55

根据我的理解,方法是可以在类上执行的任何操作。 它是编程中使用的通用术语。

在许多语言中,方法由函数和子例程表示。 大多数语言使用的主要区别是函数可以将值返回给调用者,而子例程则不能。 然而,许多现代语言只有函数,但这些函数可以选择不返回任何值。

例如,假设您想描述一只猫,并且希望它能够打哈欠。 您将创建一个具有 Yawn 方法的 Cat 类,该方法很可能是一个没有任何返回值的函数。

From my understanding a method is any operation which can be performed on a class. It is a general term used in programming.

In many languages methods are represented by functions and subroutines. The main distinction that most languages use for these is that functions may return a value back to the caller and a subroutine may not. However many modern languages only have functions, but these can optionally not return any value.

For example, lets say you want to describe a cat and you would like that to be able to yawn. You would create a Cat class, with a Yawn method, which would most likely be a function without any return value.

小矜持 2024-07-12 18:12:55

对于一阶近似,方法(在 C++ 风格的 OO 中)是成员函数的另一种说法,即属于类的函数。

在像 C/C++ 这样的语言中,你可以拥有不属于类成员的函数; 您不会将与类无关的函数称为方法。

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.

后知后觉 2024-07-12 18:12:55

恕我直言,人们只是想发明一个新词,以便当程序员想要引用对象内部的函数时,他们可以更轻松地进行交流。

如果您说的是方法,那么您指的是类内部的函数。
如果您说的是函数,那么您指的是类之外的函数。

事实上,这两个词都用来描述函数。 即使你使用错误,也不会发生任何错误。 这两个词很好地描述了您希望在代码中实现的目标。

函数是必须发挥某种作用(函数)来执行某些操作的代码。
方法是解决问题的方法

它做同样的事情。 这是同样的事情。 如果您想要超级精确并遵循约定,您可以将方法作为对象内部的函数来调用。

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.

金橙橙 2024-07-12 18:12:55

函数是主要属于面向过程编程的概念,其中函数是可以处理数据并返回值的实体。

方法是面向对象编程的概念,其中方法是一个类的成员,主要对类成员进行处理。

Function is the concept mainly belonging to Procedure oriented programming where a function is an an entity which can process data and returns you value

Method is the concept of Object Oriented programming where a method is a member of a class which mostly does processing on the class members.

或十年 2024-07-12 18:12:55

我不是专家,但这就是我所知道的:

  1. 函数是C语言术语,它指的是一段代码,函数名称将是使用该函数的标识符。

  2. 方法是面向对象的术语,通常它的函数参数中有一个 this 指针。 你不能像C那样调用这段代码,你需要使用对象来调用它。

  3. 调用方法也不同。 这里invoke的意思是找到这段代码的地址。 C/C++,链接时会使用函数符号来定位。

  4. Objec-C 是不同的。 调用意味着使用数据结构来查找地址的 C 函数。 这意味着一切在运行时都是已知的。

I am not an expert, but this is what I know:

  1. Function is C language term, it refers to a piece of code and the function name will be the identifier to use this function.

  2. Method is the OO term, typically it has a this pointer in the function parameter. You can not invoke this piece of code like C, you need to use object to invoke it.

  3. The invoke methods are also different. Here invoke meaning to find the address of this piece of code. C/C++, the linking time will use the function symbol to locate.

  4. Objecive-C is different. Invoke meaning a C function to use data structure to find the address. It means everything is known at run time.

各空 2024-07-12 18:12:55

TL;DR

函数是一段要运行的代码。
方法是对象内的函数。

函数示例:


function sum(){
  console.log("sum")l
}

方法示例:

const obj = {
a:1,
b:2,
sum(){
  }
}

这就是为什么我们说函数中的“this”关键字不是很有用,除非我们将其与 call、apply 或 bind 一起使用。因为 call、apply、bind 会调用该函数作为对象内部的方法==> 基本上它将函数转换为方法

TL;DR

A Function is a piece of code to run.
A Method is a Function inside an Object.

Example of a function:


function sum(){
  console.log("sum")l
}

Example of a Method:

const obj = {
a:1,
b:2,
sum(){
  }
}

So thats why we say that a "this" keyword inside a Function is not very useful unless we use it with call, apply or bind .. because call, apply, bind will call that function as a method inside object ==> basically it converts function to method

千鲤 2024-07-12 18:12:55

我知道很多其他人已经回答了,但我发现以下是一个简单但有效的单行答案。 虽然它看起来并不比这里的其他答案好很多,但是如果您仔细阅读它,它包含您需要了解的有关方法与函数的所有信息。

方法是具有已定义接收者的函数,在 OOP 术语中,方法是对象实例上的函数。

I know many others have already answered, but I found following is a simple, yet effective single line answer. Though it doesn't look a lot better than others answers here, but if you read it carefully, it has everything you need to know about the method vs function.

A method is a function that has a defined receiver, in OOP terms, a method is a function on an instance of an object.

北方。的韩爷 2024-07-12 18:12:55

类是一些数据和函数的集合,可以选择使用构造函数。

当您创建该特定类的实例(副本、复制)时,构造函数会初始化该类并返回一个对象。

现在类成为对象(没有构造函数)
&
函数在对象上下文中被称为方法。

所以基本上

Class <==new==>Object

Function <==new==>Method

在 java 中,通常被告知构造函数名称与类名称相同,但实际上构造函数就像实例块,静态块,但具有用户定义的返回类型(即类类型),

而类可以有静态块、实例块、构造函数、函数
对象一般只有数据和数据。 方法。

A class is the collection of some data and function optionally with a constructor.

While you creating an instance (copy,replication) of that particular class the constructor initialize the class and return an object.

Now the class become object (without constructor)
&
Functions are known as method in the object context.

So basically

Class <==new==>Object

Function <==new==>Method

In java the it is generally told as that the constructor name same as class name but in real that constructor is like instance block and static block but with having a user define return type(i.e. Class type)

While the class can have an static block,instance block,constructor, function
The object generally have only data & method.

失退 2024-07-12 18:12:55

函数 - 独立代码段中的函数,包含一些逻辑,必须独立调用 并且在类外部定义。

方法 - 方法是一段独立的代码它引用某个对象来调用,并在类内部定义。

Function - A function in an independent piece of code which includes some logic and must be called independently and are defined outside of class.

Method - A method is an independent piece of code which is called in reference to some object and are be defined inside the class.

别再吹冷风 2024-07-12 18:12:55

一般答案是:

method 有对象上下文(this 或类实例引用),

function 没有上下文(null、全局或静态) )。

但是问题的答案取决于您使用的语言术语。

  1. 在 JavaScript (ES 6) 中,您是自由的 为您想要的任何内容自定义函数上下文 (this),通常必须链接到 (this) 对象实例上下文.

  2. 在 Java 世界中,你总是会听到“只有 OOP 类/对象”,没有函数”,但是如果你仔细观察 Java 中的静态方法,它们实际上位于全局/空上下文(或类的上下文,没有实例化)中,所以只有函数而没有对象。 Java 老师可能会告诉你,函数是 C++ 中 C 的雏形,并在 Java 中被删除,但他们告诉你这是为了简化历史并避免新手提出不必要的问题。 如果你看 Java 7 版本之后,你可以发现很多纯函数编程的元素(甚至不是来自 C,但是从 1988 年开始 Lisp) 用于简化并行计算,并且它不是 OOP 类风格

  3. 在 C++ 和 D 世界中,事情更强大,并且您已经分离了函数具有方法和字段的对象。 但在实践中,您会再次看到没有 this 的函数和有 this 的方法(带有对象上下文)。

  4. 在 FreePascal/Lazarus 和 Borland Pascal/Delphi 中,有关函数和对象(变量)的分离术语和 字段)通常与 C++ 类似。

  5. Objective-C 来自 C 世界,因此必须使用方法插件将 C 函数和 Objective-C 对象分开。

  6. C# 与 Java 非常相似,但具有许多 C++ 的优点。

General answer is:

method has object context (this, or class instance reference),

function has none context (null, or global, or static).

But answer to question is dependent on terminology of language you use.

  1. In JavaScript (ES 6) you are free to customising function context (this) for any you desire, which is normally must be link to the (this) object instance context.

  2. In Java world you always hear that "only OOP classes/objects, no functions", but if you watch in detailes to static methods in Java, they are really in global/null context (or context of classes, whithout instancing), so just functions whithout object. Java teachers could told you, that functions were rudiment of C in C++ and dropped in Java, but they told you it for simplification of history and avoiding unnecessary questions of newbies. If you see at Java after 7 version, you can find many elements of pure function programming (even not from C, but from older 1988 Lisp) for simplifying parallel computing, and it is not OOP classes style.

  3. In C++ and D world things are stronger, and you have separated functions and objects with methods and fields. But in practice, you again see functions without this and methods whith this (with object context).

  4. In FreePascal/Lazarus and Borland Pascal/Delphi things about separation terms of functions and objects (variables and fields) are usually similar to C++.

  5. Objective-C comes from C world, so you must separate C functions and Objective-C objects with methods addon.

  6. C# is very similar to Java, but has many C++ advantages.

伤感在游骋 2024-07-12 18:12:55

用两个词来说:非静态(“实例”)方法采用一个指向“this”的隐藏指针(作为它们的第一个参数),这是您调用该方法的对象。

这是与常规独立函数的唯一区别,尽管是动态调度。

如果您有兴趣,请阅读下面的详细信息。

我将尽量简短并使用 C++ 作为示例,尽管我所说的内容几乎可以应用于所有语言。

  • 对于你的CPU来说,函数和方法都只是代码片段。
    时期。
  • 因此,当调用函数/方法时,它们可以采取
    参数

好吧,我说的是没有实际区别。 让我们更深入地挖掘一下:

  • 方法有两种类型:静态和非静态
  • 静态方法类似于常规函数,但在类内部声明,其作用仅类似于命名空间
  • 非静态(“实例”)方法采用隐藏的指针“这”。 这是与常规独立函数的唯一区别。

动态调度 放在一边,这意味着它就这么简单:

class User {
    public string name; // I made it public intentionally

    // Each instance method takes a hidden reference to "this"
    public void printName(/*User & this*/) {
        cout << this.name << endl;
    }
};

相当于

public getName(User & user) {
    // No syntactic sugar, passing a reference explicitly
    cout << user.name << endl;
}

所以,本质上,< code>user->printName() 只是 语法糖 >getName(用户)

如果不使用动态调度,就这样。 如果使用它,那么会涉及更多一些,但编译器仍然会发出看起来像将 this 作为第一个参数的函数。

In just 2 words: non-static ("instance") methods take a hidden pointer to "this" (as their 1st param) which is the object you call the method on.

That's the only difference with a regular standalone function, dynamic dispatching notwithstanding.

If you are interested, read the details below.

I'll try to be short and will use C++ as an example although what I say can be applied to virtually every language.

  • For your CPU, both functions and methods are just pieces of code.
    Period.
  • As such, when functions/methods are called, they can take
    parameters

Ok, I said there's no actual difference. Let's dig a bit deeper:

  • There are 2 flavors of methods: static and non-static
  • Static methods are like regular functions but declared inside the class that acts merely like a namespace
  • Non-static ("instance") methods take a hidden pointer to "this". That's the only difference with a regular standalone function.

Dynamic dispatching aside, it means it's as simple as that:

class User {
    public string name; // I made it public intentionally

    // Each instance method takes a hidden reference to "this"
    public void printName(/*User & this*/) {
        cout << this.name << endl;
    }
};

is equivalent to

public getName(User & user) {
    // No syntactic sugar, passing a reference explicitly
    cout << user.name << endl;
}

So, essentially, user->printName() is just syntactic sugar for getName(user).

If you don't use dynamic dispatch, that's all. If it is used, then it's a bit more involved, but the compiler will still emit what looks like a function taking this as a first parameter.

眼角的笑意。 2024-07-12 18:12:55

既然您提到了 Python,下面的内容可能是大多数现代面向对象语言中方法和对象之间关系的有用说明。 简而言之,他们所说的“方法”只是一个传递额外参数的函数(正如其他答案所指出的那样),但 Python 使这一点比大多数语言更加明确。

# 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")

现在比较函数 greet_with_greeter 和方法 greet:唯一的区别是第一个参数的名称(在函数中我将其称为“greeter”,在方法中我将其称为“greeter”)是“自己”)。 因此,我可以使用 greet 方法,就像使用 greet_with_greeter 函数一样(使用“点”语法来获取它,因为我在class):

Greeter.greet(hello_greeter, "World")

所以我有效地将方法变成了函数。 我可以将函数变成方法吗? 好吧,由于 Python 允许您在定义类后对其进行处理,让我们尝试一下:

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

是的,函数 greet_with_greeter 现在也称为方法 greet2。 这显示了方法和函数之间唯一真正的区别:当您通过调用 object.method(args) 来调用对象“上”的方法时,语言会神奇地将其转换为 method(对象,参数)

(面向对象的纯粹主义者可能会认为方法与函数不同,如果您深入了解高级 Python 或 Ruby - 或 Smalltalk! - 您将开始明白他们的观点。此外,某些语言还为方法提供了对对象位的特殊访问权限。但是主要的概念差异仍然是隐藏的额外参数。)

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.)

心奴独伤 2024-07-12 18:12:55

类上的方法作用于类的实例(称为对象)。

class Example
{
   public int data = 0; // Each instance of Example holds its internal data. This is a "field", or "member variable".

   public void UpdateData() // .. and manipulates it (This is a method by the way)
   {
      data = data + 1;
   }

   public void PrintData() // This is also a method
   {
      Console.WriteLine(data);
   }
}

class Program
{
   public static void Main()
   {
       Example exampleObject1 = new Example();
       Example exampleObject2 = new Example();

       exampleObject1.UpdateData();
       exampleObject1.UpdateData();

       exampleObject2.UpdateData();

       exampleObject1.PrintData(); // Prints "2"
       exampleObject2.PrintData(); // Prints "1"
   }
}

Methods on a class act on the instance of the class, called the object.

class Example
{
   public int data = 0; // Each instance of Example holds its internal data. This is a "field", or "member variable".

   public void UpdateData() // .. and manipulates it (This is a method by the way)
   {
      data = data + 1;
   }

   public void PrintData() // This is also a method
   {
      Console.WriteLine(data);
   }
}

class Program
{
   public static void Main()
   {
       Example exampleObject1 = new Example();
       Example exampleObject2 = new Example();

       exampleObject1.UpdateData();
       exampleObject1.UpdateData();

       exampleObject2.UpdateData();

       exampleObject1.PrintData(); // Prints "2"
       exampleObject2.PrintData(); // Prints "1"
   }
}
零度℉ 2024-07-12 18:12:55

函数是一组可用于操作数据的逻辑。

而方法是用于操作其所属对象的数据的函数。
因此,从技术上讲,如果您有一个与您的类不完全相关但在类中声明的函数,那么它不是方法;而是方法。 这被称为糟糕的设计。

Function is a set of logic that can be used to manipulate data.

While, Method is function that is used to manipulate the data of the object where it belongs.
So technically, if you have a function that is not completely related to your class but was declared in the class, its not a method; It's called a bad design.

離人涙 2024-07-12 18:12:55

在 OO 语言(例如 Object Pascal 或 C++)中,“方法”是与对象关联的函数。 因此,例如,“狗”对象可能具有“吠叫”功能,这将被视为“方法”。 相反,“StrLen”函数是独立的(它提供作为参数提供的字符串的长度)。 因此,它只是一个“函数”。 从技术上讲,Javascript 也是面向对象的,但与 C++、C# 或 Pascal 等成熟语言相比,它面临许多限制。 尽管如此,这种区别仍然存在。

几个额外的事实:C# 是完全面向对象的,因此您无法创建独立的“函数”。 在 C# 中,每个函数都绑定到一个对象,因此从技术上讲,它是一种“方法”。 更有趣的是,C# 中很少有人将它们称为“方法”——他们只是使用术语“函数”,因为没有任何真正的区别。

最后 - 只是为了让任何 Pascal 专家不要在这里跳到我身上 - Pascal 还区分“函数”(返回值)和不返回值的“过程”。 C# 并没有明确地做出这种区分,尽管您当然可以选择是否返回值。

In OO languages such as Object Pascal or C++, a "method" is a function associated with an object. So, for example, a "Dog" object might have a "bark" function and this would be considered a "Method". In contrast, the "StrLen" function stands alone (it provides the length of a string provided as an argument). It is thus just a "function." Javascript is technically Object Oriented as well but faces many limitations compared to a full-blown language like C++, C# or Pascal. Nonetheless, the distinction should still hold.

A couple of additional facts: C# is fully object oriented so you cannot create standalone "functions." In C# every function is bound to an object and is thus, technically, a "method." The kicker is that few people in C# refer to them as "methods" - they just use the term "functions" because there isn't any real distinction to be made.

Finally - just so any Pascal gurus don't jump on me here - Pascal also differentiates between "functions" (which return a value) and "procedures" which do not. C# does not make this distinction explicitly although you can, of course, choose to return a value or not.

七堇年 2024-07-12 18:12:55

从历史上看,“方法”是不返回值的东西,而“函数”是返回值的东西,这可能存在细微的差别。每种语言都有自己的具有特殊含义的术语词典

“C”中,单词“函数”表示程序例程

Java中,术语“函数”没有任何特殊含义。 而“方法”表示形成类的实现的例程之一。

C# 中,这将翻译为:

public void DoSomething() {} // method
public int DoSomethingAndReturnMeANumber(){} // function

但实际上,我重申这两个概念实际上没有区别。
如果您在有关 Java 的非正式讨论中使用术语“函数”,人们会认为您的意思是“方法”并继续。 不要在有关 Java 的正确文档或演示文稿中使用它,否则您会显得很傻。

Historically, there may have been a subtle difference with a "method" being something which does not return a value, and a "function" one which does.Each language has its own lexicon of terms with special meaning.

In "C", the word "function" means a program routine.

In Java, the term "function" does not have any special meaning. Whereas "method" means one of the routines that forms the implementation of a class.

In C# that would translate as:

public void DoSomething() {} // method
public int DoSomethingAndReturnMeANumber(){} // function

But really, I re-iterate that there is really no difference in the 2 concepts.
If you use the term "function" in informal discussions about Java, people will assume you meant "method" and carry on. Don't use it in proper documents or presentations about Java, or you will look silly.

风追烟花雨 2024-07-12 18:12:55

函数是一个数学概念。 例如:

f(x,y) = sin(x) + cos(y)

表示函数 f() 将返回第一个参数的正弦值加上第二个参数的余弦值。 这只是数学。 碰巧 sin() 和 cos() 也是函数。 函数还有另一个属性:对具有相同参数的函数的所有调用都应返回相同的结果。

另一方面,方法是与面向对象语言中的对象相关的函数。 它有一个隐式参数:被操作的对象(及其状态)。

因此,如果您有一个带有方法 g(x) 的对象 Z,您可能会看到以下内容:

Z.g(x) = sin(x) + cos(Z.y)

在这种情况下,参数 x 被传入,与前面的函数示例中的相同。 然而,cos() 的参数是存在于对象 Z 内部的值。Z 和存在于其中的数据 (Zy) 是 Z 的 g() 方法的隐式参数。

A function is a mathematical concept. For example:

f(x,y) = sin(x) + cos(y)

says that function f() will return the sin of the first parameter added to the cosine of the second parameter. It's just math. As it happens sin() and cos() are also functions. A function has another property: all calls to a function with the same parameters, should return the same result.

A method, on the other hand, is a function that is related to an object in an object-oriented language. It has one implicit parameter: the object being acted upon (and it's state).

So, if you have an object Z with a method g(x), you might see the following:

Z.g(x) = sin(x) + cos(Z.y)

In this case, the parameter x is passed in, the same as in the function example earlier. However, the parameter to cos() is a value that lives inside the object Z. Z and the data that lives inside it (Z.y) are implicit parameters to Z's g() method.

不知所踪 2024-07-12 18:12:55

函数或方法是一段命名的可调用代码,它执行一些操作并可选择返回一个值。

C语言中,使用术语“函数”。 Java & C#人们会说它是一个方法(在这种情况下,函数是在类/对象中定义的)。

C++ 程序员可能将其称为函数或有时称为方法(取决于他们是否正在编写过程式 C++ 代码或正在执行面向对象的 C++ 方式,而且仅使用 C/C++ 的程序员也可能将其称为函数,因为术语“方法”在 C/C++ 文献中较少使用)。

您只需调用函数的名称即可使用函数,例如

result = mySum(num1, num2);

您可以首先通过引用其对象来调用方法,例如,

result = MyCalc.mySum(num1,num2);

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);
养猫人 2024-07-12 18:12:55

方法是类的函数。 用通常的行话来说,人们到处互换方法和功能。 基本上你可以将它们视为同一件事(不确定全局函数是否称为方法)。

http://en.wikipedia.org/wiki/Method_(computer_science)

Methods are functions of classes. In normal jargon, people interchange method and function all over. Basically you can think of them as the same thing (not sure if global functions are called methods).

http://en.wikipedia.org/wiki/Method_(computer_science)

剩余の解释 2024-07-12 18:12:55

在面向对象的世界中,这两者通常用来表示同一件事。

从纯粹的数学和计算机科学的角度来看,当使用相同的参数调用时,函数将始终返回相同的结果( f(x,y) = (x + y) )。 另一方面,方法通常与类的实例相关联。 不过,大多数现代面向对象语言在很大程度上不再使用术语“函数”。 许多静态方法非常类似于函数,因为它们通常没有状态(并不总是正确)。

In OO world, the two are commonly used to mean the same thing.

From a pure Math and CS perspective, a function will always return the same result when called with the same arguments ( f(x,y) = (x + y) ). A method on the other hand, is typically associated with an instance of a class. Again though, most modern OO languages no longer use the term "function" for the most part. Many static methods can be quite like functions, as they typically have no state (not always true).

江湖正好 2024-07-12 18:12:55

假设一个函数是一个代码块(通常有自己的作用域,有时有自己的闭包),它可以接收一些参数,也可以返回一个结果。

方法是对象所拥有的函数(在某些面向对象的系统中,更正确的说法是它由类拥有)。 被对象/类“拥有”意味着您通过对象/类引用该方法; 例如,在 Java 中,如果要调用对象“door”拥有的方法“open()”,则需要编写“door.open()”。

通常方法还会获得一些额外的属性来描述它们在对象/类中的行为,例如:可见性(与面向对象的封装概念相关),它定义了可以从哪些对象(或类)调用该方法。

在许多面向对象的语言中,所有“函数”都属于某个对象(或类),因此在这些语言中,没有函数不是方法。

Let's say a function is a block of code (usually with its own scope, and sometimes with its own closure) that may receive some arguments and may also return a result.

A method is a function that is owned by an object (in some object oriented systems, it is more correct to say it is owned by a class). Being "owned" by a object/class means that you refer to the method through the object/class; for example, in Java if you want to invoke a method "open()" owned by an object "door" you need to write "door.open()".

Usually methods also gain some extra attributes describing their behaviour within the object/class, for example: visibility (related to the object oriented concept of encapsulation) which defines from which objects (or classes) the method can be invoked.

In many object oriented languages, all "functions" belong to some object (or class) and so in these languages there are no functions that are not methods.

み格子的夏天 2024-07-12 18:12:55

简单的记忆方法:

  • Function → Free(自由意味着它可以在任何地方,不需要在对象或类中)
  • M ethod → Member(对象或类的成员)

Simple way to remember:

  • Function → Free (Free means it can be anywhere, no need to be in an object or class)
  • Method → Member (A member of an object or class)
对你的占有欲 2024-07-12 18:12:55

函数方法之间主要区别的非常笼统的定义:

函数在类外部定义,而方法在类内部定义,并且是类的一部分。

A very general definition of the main difference between a Function and a Method:

Functions are defined outside of classes, while Methods are defined inside of and part of classes.

尴尬癌患者 2024-07-12 18:12:55

面向对象范式背后的思想是“对待”由......以及“对象”组成的软件。 现实世界中的对象具有属性,例如,如果您有一个员工,该员工有姓名、员工 ID、职位、所属部门等。

该对象还知道如何处理其属性并执行某些操作对他们进行操作。 假设我们想知道某个员工现在在做什么,我们会问他。

employe whatAreYouDoing.

“whatAreYouDoing”是发送给对象的“消息”。 该对象知道如何回答该问题,据说它有解决该问题的“方法”。

因此,对象必须公开其行为的方式称为方法。 因此,方法是必须“做”某事的工件对象。

其他可能的方法有

employee whatIsYourName
employee whatIsYourDepartmentsName

等。

另一方面,函数是编程语言必须计算某些数据的方式,例如,您可能有函数 addValues( 8 , 8 ) 返回 16

// pseudo-code
function addValues( int x, int y )  return x + y 
// call it 
result = addValues( 8,8 )
print result // output is 16...

自从第一个流行的编程语言(例如 fortran、c、 pascal)没有涵盖 OO 范式,他们只调用这些工件“函数”。

例如,C 中的前一个函数将是:

int addValues( int x, int y ) 
{
   return x + y;
}

说一个对象具有执行某些操作的“函数”是不“自然”的,因为函数与数学内容更相关,而 Employee 对此几乎没有数学知识,但是您可以具有与函数完全相同的方法,例如在 Java 中,这将是等效的 addValues 函数。

public static int addValues( int x, int y ) {
    return x + y;
}

看起来很熟悉? 那是因为 Java 的根源在于 C++,而 C++ 的根源在于 C。

最终只是一个概念,在实现中它们可能看起来相同,但在 OO 文档中这些被称为方法。

这是之前 Java 中的 Employee 对象的示例。

public class Employee {

    Department department;
    String name;

    public String whatsYourName(){
        return this.name;
    }
    public String whatsYourDeparmentsName(){
         return this.department.name();
    }
    public String whatAreYouDoing(){
        return "nothing";
    } 
    // Ignore the following, only set here for completness
    public Employee( String name ) {
        this.name = name;
    }

}

// Usage sample.
Employee employee = new Employee( "John" ); // Creates an employee called John

// If I want to display what is this employee doing I could use its methods.
// to know it.
String name = employee.whatIsYourName():
String doingWhat = employee.whatAreYouDoint();

// Print the info to the console.

 System.out.printf("Employee %s is doing: %s", name, doingWhat );

Output:
Employee John is doing nothing.

那么区别在于应用它的“域”。

AppleScript 有“自然语言”数学符号的想法,在某些时候 OO 也有这样的想法。 例如Smalltalk。 我希望您在阅读本文后能够更轻松地理解对象中的方法。

注意:该代码不会被编译,仅作为示例。 请随意修改帖子并添加 Python 示例。

The idea behind Object Oriented paradigm is to "treat" the software is composed of .. well "objects". Objects in real world have properties, for instance if you have an Employee, the employee has a name, an employee id, a position, he belongs to a department etc. etc.

The object also know how to deal with its attributes and perform some operations on them. Let say if we want to know what an employee is doing right now we would ask him.

employe whatAreYouDoing.

That "whatAreYouDoing" is a "message" sent to the object. The object knows how to answer to that questions, it is said it has a "method" to resolve the question.

So, the way objects have to expose its behavior are called methods. Methods thus are the artifact object have to "do" something.

Other possible methods are

employee whatIsYourName
employee whatIsYourDepartmentsName

etc.

Functions in the other hand are ways a programming language has to compute some data, for instance you might have the function addValues( 8 , 8 ) that returns 16

// pseudo-code
function addValues( int x, int y )  return x + y 
// call it 
result = addValues( 8,8 )
print result // output is 16...

Since first popular programming languages ( such as fortran, c, pascal ) didn't cover the OO paradigm, they only call to these artifacts "functions".

for instance the previous function in C would be:

int addValues( int x, int y ) 
{
   return x + y;
}

It is not "natural" to say an object has a "function" to perform some action, because functions are more related to mathematical stuff while an Employee has little mathematic on it, but you can have methods that do exactly the same as functions, for instance in Java this would be the equivalent addValues function.

public static int addValues( int x, int y ) {
    return x + y;
}

Looks familiar? That´s because Java have its roots on C++ and C++ on C.

At the end is just a concept, in implementation they might look the same, but in the OO documentation these are called method.

Here´s an example of the previously Employee object in Java.

public class Employee {

    Department department;
    String name;

    public String whatsYourName(){
        return this.name;
    }
    public String whatsYourDeparmentsName(){
         return this.department.name();
    }
    public String whatAreYouDoing(){
        return "nothing";
    } 
    // Ignore the following, only set here for completness
    public Employee( String name ) {
        this.name = name;
    }

}

// Usage sample.
Employee employee = new Employee( "John" ); // Creates an employee called John

// If I want to display what is this employee doing I could use its methods.
// to know it.
String name = employee.whatIsYourName():
String doingWhat = employee.whatAreYouDoint();

// Print the info to the console.

 System.out.printf("Employee %s is doing: %s", name, doingWhat );

Output:
Employee John is doing nothing.

The difference then, is on the "domain" where it is applied.

AppleScript have the idea of "natural language" matphor , that at some point OO had. For instance Smalltalk. I hope it may be reasonable easier for you to understand methods in objects after reading this.

NOTE: The code is not to be compiled, just to serve as an example. Feel free to modify the post and add Python example.

你曾走过我的故事 2024-07-12 18:12:55

函数是一段按名称调用的代码。 它可以传递数据进行操作(通过参数),并且可以选择返回数据(返回值)。 传递给函数的所有数据都是显式传递的。

方法是通过与对象关联的名称调用的一段代码。 在大多数方面,除了两个关键区别之外,它与函数相同:

  1. 方法是隐式传递数据以由调用它的对象进行操作。
  2. 方法能够对类中包含的数据进行操作(请记住,对象是类的实例 - 类是定义,对象是该数据的实例)。

(这是一个简化的解释,忽略了范围等问题。)

A function is a piece of code that is called by name. It can be passed data to operate on (by the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.

A method is a piece of code that is called by name that is associated with an object. In most respects, it is identical to a function except for two key differences:

  1. A method is implicitly passed data to operate on by the object on which it was called.
  2. A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).

(This is a simplified explanation, ignoring issues of scope etc.)

鼻尖触碰 2024-07-12 18:12:55

方法位于对象上或在类中是静态的。
函数独立于任何对象(并且在任何类之外)。

对于 Java 和 C#,只有方法。
对于C来说,只有函数。

对于 C++ 和 Python,这取决于您是否在课堂上。
但在基本英语中:

  • 功能:独立的特性或功能。
  • 方法:做某事的一种方式,它有不同的途径或方法,但与同一方面(又称类)相关。

A method is on an object or is static in class.
A function is independent of any object (and outside of any class).

For Java and C#, there are only methods.
For C, there are only functions.

For C++ and Python it would depend on whether or not you're in a class.
But in basic English:

  • Function: Standalone feature or functionality.
  • Method: One way of doing something, which has different approaches or methods, but related to the same aspect (aka class).
财迷小姐 2024-07-12 18:12:55

'方法''函数'的面向对象词。 这几乎就是全部内容(即,没有真正的区别)。

不幸的是,我认为这里的很多答案都延续或推进了这样的想法,即存在一些复杂的、有意义的差异。

真的——没有那么多,只是同一件事的不同说法而已。

[后期添加]


事实上,正如 Brian Neal 在对 这个问题, C++ 标准在引用成员函数时从不使用术语“方法”。 有些人可能认为这表明 C++ 并不是真正的面向对象语言;它是一种面向对象的语言。 然而,我更愿意将其视为一个迹象,表明一群非常聪明的人认为没有特别充分的理由使用不同的术语。

'method' is the object-oriented word for 'function'. That's pretty much all there is to it (ie., no real difference).

Unfortunately, I think a lot of the answers here are perpetuating or advancing the idea that there's some complex, meaningful difference.

Really - there isn't all that much to it, just different words for the same thing.

[late addition]


In fact, as Brian Neal pointed out in a comment to this question, the C++ standard never uses the term 'method' when refering to member functions. Some people may take that as an indication that C++ isn't really an object-oriented language; however, I prefer to take it as an indication that a pretty smart group of people didn't think there was a particularly strong reason to use a different term.

陪我终i 2024-07-12 18:12:55

一般来说:方法是属于类的函数,函数可以在代码的任何其他范围内,因此您可以声明所有方法都是函数,但并非所有函数都是方法:

采用以下 python 示例:

class Door:
  def open(self):
    print 'hello stranger'

def knock_door():
  a_door = Door()
  Door.open(a_door)

knock_door()

给出的示例向您展示了一个名为“Door”的类,它有一个名为“open”的方法或操作,它被称为方法,因为它是在类内部声明的。 下面还有另一部分带有“def”的代码,它定义了一个函数,它是一个函数,因为它没有在类中声明,该函数调用我们在类中定义的方法,如您所见,最后该函数被自己调用的。

正如您所看到的,您可以在任何地方调用函数,但是如果您想调用方法,则必须传递与声明方法的类相同类型的新对象(Class.method(object)),或者必须调用对象内部的方法(object.Method()),至少在Python中是这样。

将方法视为只有一个实体可以执行的操作,因此,如果您有一个 Dog 类,则仅在该类中具有一个 bark 函数是有意义的,这将是一种方法,如果您还有一个 Person 类,则有意义编写一个不属于任何类的函数“feed”,因为人类和狗都可以被喂食,并且您可以将其称为函数,因为它不属于任何特定的类。

In general: methods are functions that belong to a class, functions can be on any other scope of the code so you could state that all methods are functions, but not all functions are methods:

Take the following python example:

class Door:
  def open(self):
    print 'hello stranger'

def knock_door():
  a_door = Door()
  Door.open(a_door)

knock_door()

The example given shows you a class called "Door" which has a method or action called "open", it is called a method because it was declared inside a class. There is another portion of code with "def" just below which defines a function, it is a function because it is not declared inside a class, this function calls the method we defined inside our class as you can see and finally the function is being called by itself.

As you can see you can call a function anywhere but if you want to call a method either you have to pass a new object of the same type as the class the method is declared (Class.method(object)) or you have to invoke the method inside the object (object.Method()), at least in python.

Think of methods as things only one entity can do, so if you have a Dog class it would make sense to have a bark function only inside that class and that would be a method, if you have also a Person class it could make sense to write a function "feed" for that doesn't belong to any class since both humans and dogs can be fed and you could call that a function since it does not belong to any class in particular.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文