Python Glossary Русский

all Python 3typesterm

types.MethodType

function types

The type of a bound method: a function with an instance already attached as self. types.MethodType(func, obj) binds a function to an object by hand.

Syntax

types.MethodType(function, instance)

obj.method and Class.method are different things: the class holds a plain function (FunctionType), while every access through an instance creates a fresh bound method, so obj.m is obj.m is False — compare with == instead. A function simply assigned to an instance attribute (obj.f = func) is not bound: self is not passed and the call fails with TypeError. That is what types.MethodType(func, obj) is for. A bound method holds a strong reference to obj, which is why weakref.WeakMethod exists.

Examples

import types
class Dog:
    def bark(self):
        return 'woof'
d = Dog()
print(type(Dog.bark).__name__, type(d.bark).__name__)  # → function method
print(d.bark is d.bark, d.bark == d.bark)  # → False True
import types
class Dog:
    name = 'Rex'
def intro(self):
    return 'I am ' + self.name
d = Dog()
d.intro = types.MethodType(intro, d)
print(d.intro())  # → I am Rex

See also

Open in the full glossarydocs.python.orgReport an inaccuracy