Python:绑定未绑定方法?

Python:绑定未绑定方法?,第1张

Python:绑定未绑定方法?

所有函数也是描述符,因此你可以通过调用它们的

__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


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5640928.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存