如何检查 python 方法是否已绑定?

发布于 2024-07-06 03:08:00 字数 54 浏览 6 评论 0原文

给定一个方法的引用,有没有办法检查该方法是否绑定到一个对象? 您还可以访问它绑定到的实例吗?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

妄想挽回 2024-07-13 03:08:05

同时适用于 Python 2 和 3 的解决方案很棘手。

使用包 six ,一种解决方案可能是:

def is_bound_method(f):
    """Whether f is a bound method"""
    try:
        return six.get_method_self(f) is not None
    except AttributeError:
        return False

在 Python 2 中:

  • 常规函数不会具有 im_self 属性,因此 six.get_method_self() 将引发 AttributeError 并且返回 False
  • 未绑定方法的 im_self 属性将设置为 None,因此将返回 False
  • 绑定方法将具有 im_self code> 属性设置为非 None,因此这将返回 True

在 Python 3 中:

  • 常规函数不会具有 __self__ 属性,因此 < code>six.get_method_self() 将引发 AttributeError 并返回 False
  • 未绑定方法与常规函数相同,因此将返回 False
  • 绑定方法将设置 __self__ 属性(设置为非 None),因此这将返回 True

A solution that works for both Python 2 and 3 is tricky.

Using the package six, one solution could be:

def is_bound_method(f):
    """Whether f is a bound method"""
    try:
        return six.get_method_self(f) is not None
    except AttributeError:
        return False

In Python 2:

  • A regular function won't have the im_self attribute so six.get_method_self() will raise an AttributeError and this will return False
  • An unbound method will have the im_self attribute set to None so this will return False
  • An bound method will have the im_self attribute set to non-None so this will return True

In Python 3:

  • A regular function won't have the __self__ attribute so six.get_method_self() will raise an AttributeError and this will return False
  • An unbound method is the same as a regular function so this will return False
  • An bound method will have the __self__ attribute set (to non-None) so this will return True
清浅ˋ旧时光 2024-07-13 03:08:05

im_self 属性(仅限 Python 2)

im_self attribute (only Python 2)

雨轻弹 2024-07-13 03:08:04

所选答案几乎在所有情况下都有效。 但是,当使用所选答案检查方法是否绑定在装饰器中时,检查将失败。 考虑这个示例装饰器和方法:

def my_decorator(*decorator_args, **decorator_kwargs):
    def decorate(f):
        print(hasattr(f, '__self__'))
        @wraps(f)
        def wrap(*args, **kwargs):
            return f(*args, **kwargs)
        return wrap
    return decorate

class test_class(object):
    @my_decorator()
    def test_method(self, *some_params):
        pass

装饰器中的 print 语句将打印 False
在这种情况下,我找不到任何其他方法,只能使用参数名称检查函数参数并查找名为 self 的参数。 这也保证完美地工作,因为方法的第一个参数不强制命名为self并且可以具有任何其他名称。

import inspect

def is_bounded(function):
    params = inspect.signature(function).parameters
    return params.get('self', None) is not None

The chosen answer is valid in almost all cases. However when checking if a method is bound in a decorator using chosen answer, the check will fail. Consider this example decorator and method:

def my_decorator(*decorator_args, **decorator_kwargs):
    def decorate(f):
        print(hasattr(f, '__self__'))
        @wraps(f)
        def wrap(*args, **kwargs):
            return f(*args, **kwargs)
        return wrap
    return decorate

class test_class(object):
    @my_decorator()
    def test_method(self, *some_params):
        pass

The print statement in decorator will print False.
In this case I can't find any other way but to check function parameters using their argument names and look for one named self. This is also not guarantied to work flawlessly because the first argument of a method is not forced to be named self and can have any other name.

import inspect

def is_bounded(function):
    params = inspect.signature(function).parameters
    return params.get('self', None) is not None
御弟哥哥 2024-07-13 03:08:02

在 python 3 中,__self__ 属性在绑定方法上设置。 在普通函数(或未绑定方法,在 python 3 中只是普通函数)上,它没有设置为 None

使用这样的东西:

def is_bound(m):
    return hasattr(m, '__self__')

In python 3 the __self__ attribute is only set on bound methods. It's not set to None on plain functions (or unbound methods, which are just plain functions in python 3).

Use something like this:

def is_bound(m):
    return hasattr(m, '__self__')
沒落の蓅哖 2024-07-13 03:08:00
def isbound(method):
    return method.im_self is not None
    
def instance(bounded_method):
    return bounded_method.im_self

用户定义的方法:

当用户定义的方法对象是
通过检索用户定义创建
来自类的函数对象,其
im_self 属性为 None 并且
方法对象被认为是未绑定的。
当通过检索创建一个
用户定义的函数对象
类通过其实例之一,其
im_self 属性是实例,并且
方法对象被称为是绑定的。
无论哪种情况,新方法的
im_class 属性是来自的类
进行检索,以及
它的 im_func 属性是原始的
函数对象。

在 Python 2.6 和 3.0 中:

实例方法对象有new
对象和函数的属性
包括该方法; 新的同义词
对于 im_self 来说,是 __self__,而 im_func
也可用作 __func__。 老人
Python 中仍然支持名称
2.6,但在 3.0 中消失了。

def isbound(method):
    return method.im_self is not None
    
def instance(bounded_method):
    return bounded_method.im_self

User-defined methods:

When a user-defined method object is
created by retrieving a user-defined
function object from a class, its
im_self attribute is None and the
method object is said to be unbound.
When one is created by retrieving a
user-defined function object from a
class via one of its instances, its
im_self attribute is the instance, and
the method object is said to be bound.
In either case, the new method's
im_class attribute is the class from
which the retrieval takes place, and
its im_func attribute is the original
function object.

In Python 2.6 and 3.0:

Instance method objects have new
attributes for the object and function
comprising the method; the new synonym
for im_self is __self__, and im_func
is also available as __func__. The old
names are still supported in Python
2.6, but are gone in 3.0.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文