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

How to Bind Unbound Methods in Python Without Invoking Them?

Barbara Streisand
Release: 2024-10-30 01:22:03
Original
653 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template