Programming Search⌘K

Conceptintro

Method

Also called method, instance method, member function, receiver, bound method, unbound method, method value, method expression, self, this.

A method is a function that belongs to a type and is called on a value of it, the receiver, which the method gets as a hidden or explicit first parameter.

Applies to
core-languages

Idea

A method is a function that belongs to a type and works on one value of that type, the receiver. The call r.area() does two things: it finds area through the type of r, and it calls the function with r as an extra argument. The function body reaches the receiver through a parameter, self in Python and Rust, a named receiver in Go, and the hidden this in Java, C#, C++ and JavaScript. So a method is an ordinary function plus a rule for lookup and a rule for passing the receiver, and most languages let a program see both parts:

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height


r = Rectangle(3, 4)
print(r.area())           # a method call
print(Rectangle.area(r))  # the same function, with the receiver passed by hand
f = r.area                # a bound method: the function and r together
print(f())
print(type(f).__name__, f.__self__ is r)
Output
12
12
12
method True

r.area() and Rectangle.area(r) call the same function with the same argument. r.area without the call makes a bound method: an object that holds the function and the receiver, and calls the function with the receiver when it is called.

How it works

The receiver is the first argument. The Python tutorial states the rule: "the special thing about methods is that the instance object is passed as the first argument of the function."1 The Python descriptor guide says the same from the side of the implementation: "Methods only differ from regular functions in that the object instance is prepended to the other arguments."2 Go makes the receiver a declared parameter, written before the method name: "A method is a function with a receiver."3 Rust methods are "similar to functions",4 with self, &self or &mut self as the first parameter, and the form of that parameter says whether the method takes the value, reads it or changes it. Java, C# and C++ do not declare the receiver: the compiler adds it as the hidden parameter this, and a field name alone, such as width, means this.width.

Lookup goes through the type. A call x.m() finds m from the type of x, not from x itself. Smalltalk set the model: a class holds a method dictionary, and a message send looks up the selector in the class of the receiver, then in the superclass.5 Python, JavaScript and Ruby do the same lookup at run time, through the class or the prototype chain. Java, C#, C++, Go and Rust find the method at compile time from the static type, and a virtual method, an interface method or a trait object adds one indirect call at run time. See dynamic dispatch and objects and messages.

Bound and unbound forms. A method can be used as a value in two forms. The unbound form is the function with the receiver as its first parameter: Rectangle.area in Python, Rectangle::area in Java and Rust, Rectangle.Area in Go, and &Rectangle::area in C++. The bound form fixes one receiver and takes the other arguments only. In Python, if the name found on the class is a function, "references to both the instance object and the function object are packed into a method object".1 Go calls r.Area a method value, and the spec states that the receiver "is evaluated and saved during the evaluation of the method value".3 Java writes r::area, and C# converts the method group r.Area to a delegate. C++ has no bound method type, and code uses a lambda that captures the object.

JavaScript sets the receiver at each call. A JavaScript method is a plain function stored on the prototype, and this comes from the form of the call, not from the place where the function is defined. In r.area() it is r. In a plain call, "this typically refers to the global object (in non-strict mode) or undefined (in strict mode)".6 bind fixes the receiver: it "creates a new function that, when called, calls this function with its this keyword set to the provided value".7 Arrow functions have no this of their own and take it from the code around them.

Instance methods and static methods. A static method belongs to the type and has no receiver. The JLS states the difference: "A class method is invoked relative to the class; an instance method is invoked with respect to some particular object that is an instance of a class."8 A Java or C# static method is not the same as a Python classmethod: the Python form receives the class as its first argument, so a subclass that calls it passes the subclass, and the method can create instances of it. Python's staticmethod is the form that receives nothing.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CIdiomA function that takes a pointer to a struct as its first parameter plays the part of a method, and a struct of function pointers gives dispatch at run time.
C#Native
JavaScriptNative
TypeScriptNativeAs JavaScript, and a function can declare a this parameter so that the compiler checks the receiver; no example file because it would repeat the JavaScript one.
GoNative
RustNative
KotlinNativeMember functions, bound references such as r::area and extension functions; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLIdiomSome databases let user-defined types declare methods, and most SQL code uses functions that take the value as an argument.
BashDoes not applyBash has functions but no types that own them.
PowerShellNativeMethods in class definitions, with the receiver as $this; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML has no functions; methods of DOM elements belong to JavaScript classes.
CSSDoes not applyCSS has functions on values, such as calc(), but no types that own them.
Regular expressionsDoes not applyA pattern has no functions.
Language Verdict Mechanism
Python native def in a class body; explicit self; bound method objects
JavaScript native functions on the prototype; this set by each call; bind
TypeScript native as JavaScript, with a this parameter type for checks
Java native instance and static methods; method references r::m, T::m
Kotlin native member functions; bound references r::m; extension functions
C# native instance and static methods; delegates from method groups
Go native functions with a receiver on any named type of the package; method values and expressions
Rust native functions in impl blocks with self, &self or &mut self
C idiom functions that take a pointer to a struct as the first argument
C++ native member functions; this; const and reference qualifiers; pointers to members
Bash n/a no types with functions
PowerShell native methods in class definitions; $this
SQL idiom methods of user-defined types in some databases
Regex n/a no functions
HTML n/a no functions; methods belong to the DOM classes in JavaScript
CSS n/a no functions on values

The languages differ in how they pass the receiver and in what a method value holds. Python, Rust and Go name the receiver in the declaration, and the other languages add this without a declaration. Python, Java, C# and Go have a bound method value that holds the receiver, while JavaScript has none: reading a method gives the plain function, and the receiver is lost unless the code calls bind. Go copies the receiver into the method value when the method has a value receiver, while Python, Java and C# hold a reference to the object.

Each example file defines a rectangle with an area method and, apart from JavaScript, a scale method. It calls area in several forms: as a method call, as an unbound function that takes the receiver as an argument, and as a bound value that holds the receiver. The JavaScript file shows instead how a method loses its receiver and how bind fixes it.

PythonGitHub
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def scale(self, factor):
        self.width *= factor
        self.height *= factor


def area(r):  # a free function does the same job
    return r.width * r.height


r = Rectangle(3, 4)
unbound = Rectangle.area  # a plain function: the receiver is its first parameter
bound = r.area            # a method object: the function and r together
r.scale(2)
print(r.area(), unbound(r), bound(), area(r))
print(type(unbound).__name__, type(bound).__name__)
print(bound.__func__ is unbound, bound.__self__ is r)
print(sorted([Rectangle(5, 1), Rectangle(2, 2)], key=Rectangle.area)[0].width)
Output
48 48 48 48
function method
True True
2
  • Verdict: native. A method is a function defined in the class body, and its first parameter, by convention self, is the instance. r.area() looks up area in the class of r and calls it with r as the first argument, so Rectangle.area(r) gives the same result.
  • r.area without the call is a bound method object. It holds the function in __func__ and the instance in __self__, and it keeps working after the instance changes, because it holds the instance itself, not a copy.
  • Rectangle.area is an ordinary function, so it can be passed where a function of one argument is expected, such as the key of sorted.
#include <functional>
#include <iostream>

class Rectangle {
public:
    Rectangle(int width, int height) : width_(width), height_(height) {}
    int area() const { return width_ * height_; } // this has the type const Rectangle*
    void scale(int factor) { width_ *= factor; height_ *= factor; }

private:
    int width_;
    int height_;
};

int main() {
    Rectangle r(3, 4);
    int (Rectangle::*unbound)() const = &Rectangle::area; // a pointer to a member function
    auto bound = [&r] { return r.area(); };               // a lambda keeps a reference to r
    r.scale(2);
    std::cout << r.area() << ' ' << (r.*unbound)() << ' ' << bound() << '\n';
    std::cout << std::invoke(&Rectangle::area, r) << '\n';
}
Output
48 48 48
48
  • Verdict: native. C++ calls a method a member function. Inside it, this points to the object, and width_ means this->width_. A const after the parameter list makes this a pointer to const, so the function can be called on a const object and cannot change it.
  • &Rectangle::area is a pointer to a member function. It has no object, and the call (r.*unbound)() supplies one. std::invoke calls it with the object as the first argument. A lambda that captures the object binds it.
JavaGitHub
import java.util.function.Function;
import java.util.function.Supplier;

public class Main {
  static final class Rectangle {
    private int width;
    private int height;

    Rectangle(int width, int height) {
      this.width = width;
      this.height = height;
    }

    int area() {
      return this.width * this.height; // this is the receiver
    }

    void scale(int factor) {
      width *= factor; // this. is implied
      height *= factor;
    }

    static int area(int width, int height) { // a static method: no receiver
      return width * height;
    }
  }

  public static void main(String[] args) {
    Rectangle r = new Rectangle(3, 4);
    Supplier<Integer> bound = r::area;                 // the receiver is fixed
    Function<Rectangle, Integer> unbound = Rectangle::area; // the receiver is the argument
    r.scale(2);
    System.out.println(r.area() + " " + bound.get() + " " + unbound.apply(r));
    System.out.println(Rectangle.area(6, 8));
  }
}
Output
48 48 48
48
  • Verdict: native. Every method is declared in a class. An instance method has the hidden receiver this, and a static method has none. The JLS calls a static method a class method, which is invoked relative to the class, not to an object.
  • A method reference r::area binds the receiver, and Rectangle::area takes the receiver as the first argument of the functional interface. The compiler picks the instance method or the static method of the same name by the target type.
using System;

var r = new Rectangle(3, 4);
Func<int> bound = r.Area;                 // a delegate with the receiver fixed
Func<Rectangle, int> unbound = x => x.Area();
r.Scale(2);
Console.WriteLine($"{r.Area()} {bound()} {unbound(r)}");
Console.WriteLine(bound.Target == r);
Console.WriteLine(Rectangle.AreaOf(6, 8));

class Rectangle
{
    private int width, height;

    public Rectangle(int width, int height)
    {
        this.width = width;
        this.height = height;
    }

    public int Area() => width * height;

    public void Scale(int factor)
    {
        width *= factor;
        height *= factor;
    }

    public static int AreaOf(int width, int height) => width * height;
}
Output
48 48 48
True
48
  • Verdict: native. A method is declared in a class or a struct, and an instance method has the hidden receiver this. A static method has no receiver.
  • A method group such as r.Area converts to a delegate. The delegate stores the receiver in its Target property, so bound() sees the change that Scale made. For the unbound form, C# code usually writes a lambda that takes the receiver.
JavaScriptGitHub
"use strict";

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  area() {
    return this.width * this.height;
  }
}

const r = new Rectangle(3, 4);
console.log(r.area());
console.log(Rectangle.prototype.area.call(r)); // pass the receiver by hand

const bound = r.area.bind(r);
console.log(bound());

const arrow = () => r.area(); // an arrow function keeps r in a closure
console.log(arrow());

const lost = r.area; // the function only: the receiver is lost
try {
  lost();
} catch (e) {
  console.log(e.constructor.name);
}
Output
12
12
12
12
TypeError
  • Verdict: native. Methods live on the prototype of the class, and this is the receiver. JavaScript sets this from the form of each call: in r.area() it is r.
  • A method read without a call is the plain function. Called alone, as lost(), it gets this as undefined in strict mode, and class bodies are always strict, so this.width throws a TypeError.
  • bind makes a function with a fixed this. An arrow function that calls the method is the other common fix, for example for event handlers and callbacks.
package main

import "fmt"

type Rectangle struct{ width, height int }

func (r Rectangle) Area() int { return r.width * r.height }

func (r *Rectangle) Scale(factor int) {
	r.width *= factor
	r.height *= factor
}

func main() {
	r := Rectangle{3, 4}
	value := r.Area         // a method value: r is copied now
	expr := Rectangle.Area  // a method expression: the receiver is the first argument
	scale := (*Rectangle).Scale
	scale(&r, 2)
	fmt.Println(r.Area(), value(), expr(r))
}
Output
48 12 48
  • Verdict: native. A method is a function with a receiver. The receiver is a named parameter, declared before the method name, and the method can belong to any named type of the same package.
  • r.Area without a call is a method value. Go evaluates and saves the receiver at that moment, and Area has a value receiver, so value() still sees the 3 by 4 rectangle after the scale: it prints 12, not 48.
  • Rectangle.Area is a method expression: a function whose first parameter is the receiver. A method with a pointer receiver has the method expression (*Rectangle).Scale.
RustGitHub
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }

    fn scale(&mut self, factor: u32) {
        self.width *= factor;
        self.height *= factor;
    }
}

fn main() {
    let mut r = Rectangle { width: 3, height: 4 };
    r.scale(2); // the same as Rectangle::scale(&mut r, 2)
    let unbound: fn(&Rectangle) -> u32 = Rectangle::area;
    let bound = || r.area(); // a closure borrows r
    println!("{} {} {}", r.area(), Rectangle::area(&r), unbound(&r));
    println!("{}", bound());
    let mut list = vec![Rectangle { width: 5, height: 1 }, Rectangle { width: 2, height: 2 }];
    list.sort_by_key(Rectangle::area);
    println!("{}", list[0].width);
}
Output
48 48 48
48
2
  • Verdict: native. Methods are functions in an impl block whose first parameter is self, &self or &mut self. The form of the receiver says whether the method takes the value, reads it or changes it.
  • r.scale(2) is the method call syntax for Rectangle::scale(&mut r, 2). Rust adds the & or &mut itself, by automatic referencing.
  • Rectangle::area is a path to an ordinary function, so it can be passed to sort_by_key. A closure that borrows r is the bound form.
  • Class methods and static methods. Python has classmethod, which receives the class, and staticmethod, which receives nothing. Java, C# and C++ have only the static form. Kotlin uses a companion object for members of the class.
  • Extension methods. C# extension methods and Kotlin extension functions are static functions that the call syntax lets a program call like methods, without changing the type. Go and Rust allow methods only in the package or crate that owns the type, and Rust adds methods to types of other crates through local traits.
  • Explicit receivers in C++. C++23 lets a member function declare its object parameter with this, as in int area(this const Rectangle& self), which is close to the Python and Rust form.9
  • Const and mutating methods. C++ marks a method that does not change the object with const, Rust with &self, and Swift requires mutating on a method that changes a struct.
  • Methods without classes. C code writes a method as a function whose first parameter is a pointer to a struct, such as rect_area(const struct rect *r). Go and Rust put methods on structs and on other named types. See define a method on a type and define a class.
  • Multimethods. Common Lisp and Julia choose a method from the types of all the arguments, not only from the first one. See dynamic dispatch.
  • Functions as values. A bound method is a closure over its receiver. See closures and higher-order functions.

Pitfalls

  • A lost receiver in JavaScript. Passing r.area as a callback passes the function only, and the call gets this as undefined in strict mode, which throws a TypeError at the first field access. The example file shows the error and the two fixes, bind and an arrow function.
  • A missing self in Python. A method defined without the self parameter still gets the instance as its first argument when it is called on an instance, so the call fails:
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area():  # the self parameter is missing
        return 0


r = Rectangle(3, 4)
try:
    r.area()
except TypeError as e:
    print(type(e).__name__)

print(r.area is r.area)  # each lookup makes another bound method
print(r.area == r.area)  # they compare equal: same function, same instance
Output
TypeError
False
True

The program also shows that each read of r.area makes another bound method object, so is gives False for two reads, while == gives True.

  • A Go method value copies the receiver. For a method with a value receiver, v := r.Area copies r at that point, and later changes to r do not reach v(). The example file shows value() printing the area from before the scale. A method with a pointer receiver saves the pointer, so it sees the changes.
  • A Java static method in place of a Python classmethod. Code ported from Python that turns a classmethod factory into a Java static method loses the class argument, so a subclass gets instances of the base class. Java code passes a factory or overrides the method in the subclass.
  • Calling an instance method from a static context. A static method has no receiver, so a call to an instance method or a read of an instance field without an object is a compile error in Java and C#.
  • Receivers in Go defer and go statements. In Go, defer r.Close() and go r.Run() evaluate the receiver when the statement runs, not when the call happens.

Cost

A method call that the compiler resolves at compile time costs the same as a function call with one more argument, and the compiler can inline it. A call through a virtual function, an interface or a trait object adds one indirect call, which blocks inlining unless the compiler can prove the type. Python and JavaScript look up the method at run time, and their implementations cache the result of the lookup at each call site. A bound method value costs an allocation in Python, in Go when it escapes, and for a Java method reference or a C# delegate that captures a receiver.

History

Simula 67 attached procedures to classes, and Smalltalk, built at Xerox PARC by Alan Kay, Dan Ingalls, Adele Goldberg and others in the 1970s, used the word method for the code that answers a message: an object receives a message, and its class maps the selector of the message to a method.5 Wikipedia describes a method as "a procedure associated with an object, and generally also a message".10 Bjarne Stroustrup's C++ used the term member function, and the C++ standard still uses it.9 Python, released in 1991, made the receiver an explicit parameter, and Go in 2009 and Rust in 2015 kept the receiver as a declared parameter but dropped classes.

References

  1. 9. Classes, The Python Tutorial, 9.3.4 Method Objects
  2. Descriptor Guide, Python HOWTOs, Functions and methods
  3. The Go Programming Language Specification, Method declarations; Method values; Method expressions
  4. Methods, The Rust Programming Language, Method Syntax; Where's the -> Operator?
  5. Smalltalk, Wikipedia, Reflection; Image-based persistence
  6. this, MDN Web Docs, Function context
  7. Function.prototype.bind(), MDN Web Docs, Description
  8. Chapter 8, Classes, The Java Language Specification, Java SE 25 Edition, 8.4.3.2 static Methods
  9. Non-static member functions, cppreference.com, Introduction; Explicit object member functions
  10. Method (computer programming), Wikipedia, Introduction; Member functions in C++

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/HN1R5F/text.yaml