有人能简单解释OOP环境中的方法与函数吗?
当前回答
函数是执行特定任务的一组指令或过程。它可以用来将代码分割成易于理解的部分,这些部分也可以被调用或重用。
方法是可以对对象执行的操作。它也称为存储为对象财产的函数。
主要区别:函数不需要任何对象并且是独立的,而方法是一个函数,它与任何对象链接。
//firstName() is the function
function firstName(){
cosole.log('John');
}
firstName() //Invoked without any object
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
};
//person.name is the method
person.name = function() {
return this.firstName + " " + this.lastName;
};
document.getElementById("demo").innerHTML =
"My father is " + person.name() //performs action on object;
其他回答
“method”是“function”的面向对象词。这几乎就是它的全部(即,没有真正的区别)。
不幸的是,我认为这里的很多答案都在延续或推进一种观点,即存在一些复杂而有意义的差异。
真的-没有那么多,只是对同一件事用不同的词。
[后期添加]
事实上,正如BrianNeal在对这个问题的评论中指出的那样,C++标准在引用成员函数时从不使用“方法”一词。有些人可能认为这表明C++并不是真正的面向对象语言;然而,我更倾向于将其作为一种迹象,即一群相当聪明的人并不认为有特别强烈的理由使用不同的术语。
从历史上看,“方法”是不返回值的东西,而“函数”是返回值的,这两者之间可能存在着微妙的区别。每种语言都有自己的具有特殊含义的词汇。
在“C”中,“函数”一词表示程序例程。
在Java中,术语“函数”没有任何特殊含义。而“方法”是指构成类实现的例程之一。
在C#中,这可以翻译为:
public void DoSomething() {} // method
public int DoSomethingAndReturnMeANumber(){} // function
但实际上,我再次重申,这两个概念实际上没有什么不同。如果你在关于Java的非正式讨论中使用“函数”一词,人们会认为你的意思是“方法”并继续下去。不要在有关Java的适当文档或演示中使用它,否则你会看起来很傻。
函数是执行特定任务的一组指令或过程。它可以用来将代码分割成易于理解的部分,这些部分也可以被调用或重用。
方法是可以对对象执行的操作。它也称为存储为对象财产的函数。
主要区别:函数不需要任何对象并且是独立的,而方法是一个函数,它与任何对象链接。
//firstName() is the function
function firstName(){
cosole.log('John');
}
firstName() //Invoked without any object
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
};
//person.name is the method
person.name = function() {
return this.firstName + " " + this.lastName;
};
document.getElementById("demo").innerHTML =
"My father is " + person.name() //performs action on object;
既然您提到了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”,在方法中我称其为“self”)。因此,我可以以与使用greet_with_greeter函数完全相同的方式使用greet方法(使用“dot”语法,因为我在类中定义了它):
Greeter.greet(hello_greeter, "World")
所以我已经有效地将一个方法变成了一个函数。我能把函数变成方法吗?好吧,因为Python允许您在定义类之后处理它们,所以让我们尝试:
Greeter.greet2 = greet_with_greeter
hello_greeter.greet2("World")
是的,函数greet_with_greeter现在也称为方法greet2。这显示了方法和函数之间唯一真正的区别:当您通过调用object.method(args)“对”对象调用方法时,语言会神奇地将其转换为方法(object,args)。
(OO纯粹主义者可能会认为方法与函数不同,如果你进入高级Python或Ruby-或Smalltalk!-你会开始明白他们的观点。此外,一些语言赋予方法特殊的对象访问权限。但主要的概念区别仍然是隐藏的额外参数。)
面向对象范例背后的思想是“处理”软件由。。好的“对象”。现实世界中的对象具有财产,例如,如果您有一个Employee,则该员工具有姓名、员工id、职位、他属于某个部门等。
对象还知道如何处理其属性并对其执行一些操作。比方说,如果我们想知道员工现在在做什么,我们会问他。
employe whatAreYouDoing.
“whatAreYouDoing”是发送给对象的“消息”。对象知道如何回答这些问题,据说它有解决问题的“方法”。
因此,对象必须公开其行为的方式称为方法。因此,方法是工件对象必须“做”的事情。
其他可能的方法有
employee whatIsYourName
employee whatIsYourDepartmentsName
etc.
另一方面,函数是编程语言计算某些数据的方式,例如,您可以使用返回16的函数addValues(8,8)
// 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;
}
说一个对象有一个“函数”来执行某些操作是不“自然”的,因为函数更多地与数学相关,而雇员几乎没有数学知识,但你可以有与函数完全相同的方法,例如在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有一种“自然语言”matphor的概念,在某种程度上OO也有这种想法。例如Smalltalk。我希望在阅读了这篇文章之后,您可以更容易地理解对象中的方法。
注意:代码不是要编译的,只是作为示例。请随意修改文章并添加Python示例。