【问题标题】:How to find instance of a bound method in Python?如何在 Python 中查找绑定方法的实例?
【发布时间】:2011-06-08 10:52:07
【问题描述】:
>>> class A(object):  
...         def some(self):  
...                 pass  
...  
>>> a=A()  
>>> a.some  
<bound method A.some of <__main__.A object at 0x7f0d6fb9c090>>

IOW,我只需要在“a.some”移交后才能访问“a”。

【问题讨论】:

    标签: python class methods


    【解决方案1】:

    从 python 2.6 开始你可以使用特殊属性__self__:

    >>> a.some.__self__ is a
    True
    

    im_self 在 py3k 中被淘汰。

    详情请见inspect module in the Python Standard Library.

    【讨论】:

    • 只是为了完全清楚:如果您有 Python 3,请使用它。如果您使用的是 Python 2,则相当于其他人发布的 im_self
    • 这似乎不适用于 dunder 方法,例如在原始示例中,A().__init__.__self__A().__eq__.__self__ 不存在。知道是否有替代方案吗?
    【解决方案2】:

    我猜你想要这样的东西:

    >>> a = A()
    >>> m = a.some
    >>> another_obj = m.im_self
    >>> another_obj
    <__main__.A object at 0x0000000002818320>
    

    im_self 是类实例对象。

    【讨论】:

      【解决方案3】:

      试试下面的代码,看看是否对你有帮助:

      a.some.im_self
      

      【讨论】:

        【解决方案4】:
        >>> class A(object):
        ...   def some(self):
        ...     pass
        ...
        >>> a = A()
        >>> a
        <__main__.A object at 0x7fa9b965f410>
        >>> a.some
        <bound method A.some of <__main__.A object at 0x7fa9b965f410>>
        >>> dir(a.some)
        ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'im_class', 'im_func', 'im_self']
        >>> a.some.im_self
        <__main__.A object at 0x7fa9b965f410>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-02-17
          • 2020-12-24
          • 1970-01-01
          • 2018-06-28
          • 2012-01-14
          • 2020-07-17
          • 1970-01-01
          相关资源
          最近更新 更多