所有函数也是描述符,因此你可以通过调用它们的
__get__方法来绑定它们:
bound_handler = handler.__get__(self, MyWidget)
这是R. Hettinger 关于描述符的出色指南。
作为一个独立的例子,请参考Keith的 评论:
def bind(instance, func, as_name=None): """ Bind the function *func* to *instance*, with either provided name *as_name* or the existing name of *func*. The provided *func* should accept the instance as the first argument, i.e. "self". """ if as_name is None: as_name = func.__name__ bound_method = func.__get__(instance, instance.__class__) setattr(instance, as_name, bound_method) return bound_methodclass Thing: def __init__(self, val): self.val = valsomething = Thing(21)def double(self): return 2 * self.valbind(something, double)something.double() # returns 42



