Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 508
willc2 Avatar asked Sep 30 '08 23:09

willc2


People also ask

What is the difference between function and a method?

A function is a set of instructions or procedures to perform a specific task, and a method is a set of instructions that are associated with an object.

What's the difference between methods and functions in Python?

Functions can be called only by its name, as it is defined independently. But methods can't be called by its name only, we need to invoke the class by a reference of that class in which it is defined, i.e. method is defined within a class and hence they are dependent on that class.


1 Answers

A function is a piece of code that is called by name. It can be passed data to operate on (i.e. 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 a 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 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.)

like image 164
Andrew Edgecombe Avatar answered Sep 22 '22 04:09

Andrew Edgecombe