Conceptintro
Method
Also called member function, instance method, static method, associated function.
A method is a function that belongs to a type. It gets a value of the type, the receiver, as an extra parameter, and a program calls it with the receiver before a dot, as in r.area().
- Applies to
- core-languages
Idea
A method is a function that belongs to a type. It works on one value of that type, called the receiver. A program calls a function as area(r), and it calls a method as r.area(). The receiver comes before the dot, and the method gets it as an extra parameter.
The Go specification says it in one line: "A method is a function with a receiver."1 The Rust book compares the two: "Methods are similar to functions: We declare them with the fn keyword and a name, they can have parameters and a return value, and they contain some code that’s run when the method is called from somewhere else."2 The difference is that methods "are defined within the context of a struct (or an enum or a trait object, which we cover in Chapter 6 and Chapter 18, respectively), and their first parameter is always self, which represents the instance of the struct the method is being called on"2.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def area(rectangle):
return rectangle.width * rectangle.height
r = Rectangle(3, 4)
print(area(r))
print(r.area())
12
12
The function area and the method Rectangle.area do the same work. The function takes the rectangle as a normal parameter. The method takes it as self, and the call r.area() passes r without writing it in the parentheses.
This page compares methods with functions. Method describes methods from the side of objects and classes: bound and unbound methods, lookup through the type and this.
How it works
- The declaration. A method is declared inside a class, a struct or an
implblock, or with a receiver parameter in Go. The declaration ties the method to one type. - The receiver parameter. The method has one more parameter than its call shows. Python names it
selfin the parameter list. Python says that "the special thing about methods is that the instance object is passed as the first argument of the function"3. Java, C#, C++, JavaScript and TypeScript add the parameterthiswithout a declaration. - The call. A call
r.area()finds the method through the type ofr, then calls it withras the receiver. The rest of the call works as a Function call. - The function form. Many languages can also call a method as a plain function with the receiver as the first argument. In Go, "T.M is a function that is callable as a regular function with the same arguments as M prefixed by an additional argument that is the receiver of the method"1. In Rust, a method "may be invoked using the method call operator, for example, x.foo(), as well as the usual function call notation"4.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has member functions in classes, and a companion object holds functions that belong to the class. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | Standard SQL queries call functions, not methods. Some databases add methods to user-defined types, but most code uses plain functions. |
| Bash | Does not apply | Bash has no types that hold functions, so it has no methods. A Bash function takes all its data as arguments or global variables. |
| PowerShell | Native | A PowerShell class can define methods, and the receiver is $this. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is a markup language and has no methods. Methods of the DOM objects belong to JavaScript. |
| CSS | Does not apply | CSS has no types with methods. |
| Regular expressions | Does not apply | A regular expression has no functions and no methods. |
- Python. A method is a function defined in a class body. Its first parameter is the receiver, by convention
self. Inside the method, the code reads the fields throughself: "There is no shorthand for referencing data attributes (or other methods!) from within methods."3 - JavaScript. "A method is a function which is a property of an object."5 The object can be a class instance or a plain object literal. The receiver is
this. - TypeScript. "A function property on a class is called a method."6 Methods have the same type annotations as functions.
- Java. All functions are methods. A
staticmethod has no receiver: "A class method is always invoked without reference to a particular object."7 "An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body."7 - C#. "Methods are declared in a class, struct, or interface"8. As in Java, a
staticmethod has no receiver, and "The static member is always accessed by the class name, not the instance name."9 - C. C has no methods. "each function definition must appear at file scope"10, so a struct cannot hold a function. A C program writes a function whose first parameter is a pointer to the struct.
- C++. C++ has free functions and member functions. "A non-static member function is a function that is declared in a member specification of a class without a static or friend specifier"11.
- Go. Go has no classes. A method is a function with a receiver parameter before its name. The receiver type "must be a defined type T or a pointer to a defined type T"1, and it "must be declared in the same package as the method"1. So a Go program can put methods on any type that it defines, such as
type Celsius float64. - Rust. Methods are in
implblocks, and the receiver isself,&selfor&mut self. Animplblock can be for a struct or for an enum2. A function in animplblock with noselfis an associated function and not a method2. - Bash. Bash has no types with functions, so it has no methods.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
@staticmethod
def square(side):
return Rectangle(side, side)
r = Rectangle(3, 4)
print(r.area())
print(Rectangle.square(5).area())
12
25
- Verdict: native.
areais an instance method with the receiverself.squareis a static method, which has no receiver.
#include <iostream>
struct Rectangle {
int width;
int height;
int area() const {
return width * height;
}
static Rectangle square(int side) {
return Rectangle{side, side};
}
};
int main() {
Rectangle r{3, 4};
std::cout << r.area() << "\n";
std::cout << Rectangle::square(5).area() << "\n";
}
12
25
- Verdict: native.
areais a non-static member function, markedconstbecause it does not change the object.squareis a static member function.
public class Main {
static class Rectangle {
final int width;
final int height;
Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
int area() {
return width * height;
}
static Rectangle square(int side) {
return new Rectangle(side, side);
}
}
public static void main(String[] args) {
Rectangle r = new Rectangle(3, 4);
System.out.println(r.area());
System.out.println(Rectangle.square(5).area());
}
}
12
25
- Verdict: native. All Java functions are methods.
areais an instance method, andsquareis astaticmethod with no receiver.
#include <stdio.h>
struct rectangle {
int width;
int height;
};
static int rectangle_area(const struct rectangle *r) {
return r->width * r->height;
}
static struct rectangle rectangle_square(int side) {
struct rectangle r = {side, side};
return r;
}
int main(void) {
struct rectangle r = {3, 4};
struct rectangle s = rectangle_square(5);
printf("%d\n", rectangle_area(&r));
printf("%d\n", rectangle_area(&s));
return 0;
}
12
25
- Verdict: idiom. C has no methods. The functions take a pointer to the struct as the first parameter, which works as the receiver.
using System;
struct Rectangle
{
public int Width;
public int Height;
public Rectangle(int width, int height)
{
Width = width;
Height = height;
}
public int Area()
{
return Width * Height;
}
public static Rectangle Square(int side)
{
return new Rectangle(side, side);
}
}
class Program
{
static void Main()
{
var r = new Rectangle(3, 4);
Console.WriteLine(r.Area());
Console.WriteLine(Rectangle.Square(5).Area());
}
}
12
25
- Verdict: native.
Areais an instance method of a struct, andSquareis astaticmethod that the program calls on the type.
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
static square(side) {
return new Rectangle(side, side);
}
}
const r = new Rectangle(3, 4);
console.log(r.area());
console.log(Rectangle.square(5).area());
12
25
- Verdict: native.
areais a method on the class, and its receiver isthis.squareis a static method, which the program calls on the class.
class Rectangle {
width: number;
height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
area(): number {
return this.width * this.height;
}
static square(side: number): Rectangle {
return new Rectangle(side, side);
}
}
const r = new Rectangle(3, 4);
console.log(r.area());
console.log(Rectangle.square(5).area());
12
25
- Verdict: native. Methods have the same type annotations as functions. The receiver is
this.
package main
import "fmt"
type Rectangle struct {
Width, Height int
}
func (r Rectangle) Area() int {
return r.Width * r.Height
}
func Square(side int) Rectangle {
return Rectangle{side, side}
}
func main() {
r := Rectangle{3, 4}
fmt.Println(r.Area())
fmt.Println(Square(5).Area())
}
12
25
- Verdict: native.
Areais a method with the receiverr. Go has no static methods, soSquareis a plain function of the package.
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn square(side: u32) -> Self {
Self {
width: side,
height: side,
}
}
}
fn main() {
let r = Rectangle {
width: 3,
height: 4,
};
println!("{}", r.area());
println!("{}", Rectangle::square(5).area());
}
12
25
- Verdict: native.
areais a method because its first parameter is&self.squareis an associated function with noself, and the program calls it withRectangle::square.
Variations and related ideas
- Static methods. A static method in Java or C# and an associated function in Rust belong to a type but have no receiver. They are plain functions in the namespace of the type72.
- Methods on types that are not classes. Go puts methods on any defined type in the package1, and Rust puts them on structs and enums2. A method does not need a class.
- Value and pointer receivers. Go and Rust let the method choose if it gets a copy of the receiver or a reference to it. See the pitfall below.
- Method or function. The Rust book says: "The main reason for using methods instead of functions, in addition to providing method syntax and not having to repeat the type of self in every method’s signature, is for organization."2 A method keeps the operations of a type in one place.
- Overriding. A subclass can give its own version of a method, and the call chooses the version from the type of the receiver at run time. Wikipedia says that "One of the most important capabilities that a method provides is method overriding"12. See Dynamic dispatch.
- Extension methods. C# and Kotlin can add methods to a type without changing it. See Extension methods.
- Overloading. A class can have several methods with one name and different parameters. See Overloading.
Pitfalls
A field name without self in Python
A Python method must read and write fields through self. A name without self. is a local variable of the method:
This code runs but gives a wrong answer on purpose.
class Counter:
def __init__(self):
self.count = 0
def increment(self):
count = self.count + 1
c = Counter()
c.increment()
c.increment()
print(c.count)
0
count = self.count + 1 makes a local variable count and drops it when the method returns. Python has "no shorthand for referencing data attributes"3. Write self.count = self.count + 1.
A value receiver in Go changes a copy
In Go, the receiver "behaves exactly as if it were an argument to the method"13. A method with a value receiver gets a copy:
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
type Counter struct {
count int
}
func (c Counter) Increment() {
c.count++
}
func main() {
var c Counter
c.Increment()
c.Increment()
fmt.Println(c.count)
}
0
The Go FAQ asks if the method needs to modify the receiver, and says: "If it does, the receiver must be a pointer."13 It also says that a value method "is called with a copy of the caller’s argument (that’s the definition of passing a value), so changes it makes will be invisible to the caller"13. Write func (c *Counter) Increment().
Cost
A method call that the compiler resolves at compile time costs the same as a function call with one more argument. A call that chooses the method at run time from the type of the receiver costs one more lookup. Dynamic dispatch describes this cost.
History
Simula 67 introduced classes with procedures in them. Dahl and Nygaard "presented their paper on class and subclass declarations at the IFIP Working Conference on simulation languages in Oslo, May 1967"14. Smalltalk used the word method for the code that a class runs for a message. "Sending a message to an object at the most abstract involves fetching the class of the receiver (the object being sent the message) and looking up the message's selector in the class's method dictionary"15.
Go and Rust separate methods from classes. Go allows methods on any defined type of a package1, and Rust puts methods in impl blocks for structs and enums2.
References
- The Go Programming Language Specification, Method declarations; Method expressions
- Methods, The Rust Programming Language, Method Syntax; Associated Functions
- Classes, The Python Tutorial, 9.3.4 Method Objects; 9.4 Random Remarks
- Associated Items, The Rust Reference, items.associated.fn.method.intro
- Method, MDN Web Docs Glossary, the whole page
- Classes, The TypeScript Handbook, Methods
- Classes, The Java Language Specification, Java SE 25 Edition, 8.4.3.2 static Methods
- Methods, C# Programming Guide, Method signatures
- Static Classes and Static Class Members, C# Programming Guide, Static Members
- Functions, C reference, cppreference.com, Explanation
- Non-static member functions, C++ reference, cppreference.com, the introduction
- Method (computer programming), Wikipedia, the introduction
- Frequently Asked Questions, The Go Programming Language, Should I define methods on values or pointers?
- Simula, Wikipedia, History
- Smalltalk, Wikipedia, Messages
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag Z3ZCTB Edit this page History Report an error Markdown