zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python: make function to be a bounded method

Python to be Function method Make
2023-09-11 14:16:16 时间

 

 所有function都有 __get__ 用于实现绑定

 

 

 

__get__

class B:
    def __init__(self, v):
        self._v = v

    def v(self):
        return self._v


def bind(instance, func, name=None):
    if name is None:
        name = func.__name__
    bounded = func.__get__(instance, instance.__class__)
    setattr(instance, name, bounded)
    return bounded


def double(self):
    return 2 * self._v


print(getattr(B.v, '__get__'))
print(B.v)

b = B(55)
print(bind(b, double))
print(b.double())

f = B.v.__get__(b, int)
print(f, b)
print(f())
print(f.__class__, )

 

types.MethodType

import types


def f(self):
    print(self)


class B:
    ...


method = types.MethodType(f, B())
print(method)
print(method())

 

 

functools.partial

import functools
import types


def f(self):
    print(self)


class B:
    ...


method = functools.partial(f, B())
print(method)
print(method())

 

 

import functools
import types


def f(self):
    print(self)


class B:
    ...


b = B()

b.method = (lambda self: lambda: f(self))(b)
print(b.method)
print(b.method())