Home  >  Article  >  Backend Development  >  How to Bind Unbound Methods in Python Without Invoking Them?

How to Bind Unbound Methods in Python Without Invoking Them?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 01:22:03546browse

How to Bind Unbound Methods in Python Without Invoking Them?

Unbinding the Gordian Knot: Binding Unbound Methods Seamlessly

In Python, binding unbound methods without invoking them can present a coding challenge. Consider this scenario:

<code class="python">class MyWidget(wx.Window):
    buttons = [("OK", OnOK), ("Cancel", OnCancel)]

    def setup(self):
        for text, handler in MyWidget.buttons:
            b = wx.Button(parent, label=text).bind(wx.EVT_BUTTON, handler)</code>

Here, handler represents an unbound method, leading to runtime errors. While functools.partial offers a workaround, Python's innate descriptor capabilities provide an elegant solution.

Unveiling the Power of Descriptors

All functions in Python possess intrinsic descriptor properties. By leveraging their __get__ method, unbound methods can be bound to an instance:

<code class="python">bound_handler = handler.__get__(self, MyWidget)</code>

This technique enables binding of unbound methods without triggering their execution.

A Comprehensive Example

To illustrate, let's implement a custom bind function:

<code class="python">def bind(instance, func, as_name=None):
    if as_name is None:
        as_name = func.__name__
    bound_method = func.__get__(instance, instance.__class__)
    setattr(instance, as_name, bound_method)
    return bound_method</code>

Utilizing this bind function, we can achieve the desired functionality:

<code class="python">class Thing:
    def __init__(self, val):
        self.val = val

something = Thing(21)

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

bind(something, double)
something.double()  # returns 42</code>

By embracing the power of descriptors, we effortlessly bind unbound methods, unlocking a myriad of coding possibilities without compromising on Pythonic principles.

The above is the detailed content of How to Bind Unbound Methods in Python Without Invoking Them?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn