代码之家  ›  专栏  ›  技术社区  ›  Jason DeFontes

在Python中,你能调用类A的实例方法,但传入类B的实例吗?

  •  6
  • Jason DeFontes  · 技术社区  · 17 年前

    为了重用一些被定义为不同类的实例方法的现有代码,我打算做以下事情:

    class Foo(object):
      def __init__(self):
        self.name = "Foo"
    
      def hello(self):
        print "Hello, I am " + self.name + "."
    
    class Bar(object):
      def __init__(self):
        self.name = "Bar"
    
    
    bar = Bar()
    Foo.hello(bar)
    

    但这导致:

    TypeError:必须以Foo实例作为第一个参数调用未绑定方法hello()(改为获取Bar实例)

    这样的事情可能吗?


    我本应明确表示,我知道这是个坏主意。显然,真正的解决方案是进行一些重构。我只是想一定有办法,事实证明是有办法的。

    4 回复  |  直到 17 年前
        1
  •  9
  •   Jason DeFontes    17 年前

    看起来这行得通:

    Foo.hello.im_func(bar)
    

    this

        2
  •  5
  •   Brian    17 年前

    之所以会发生这种情况,是因为python将类函数包装为执行此类型检查的“未绑定方法”。这其中涉及的决策有一些描述 here .

        3
  •  2
  •   Community Mohan Dere    9 年前

    对于Python 3,没有更多 <unbound method C.x> <function __main__.C.x> !

    这可能意味着不应该考虑原始问题中的代码/the/off。Python在任何情况下都是关于鸭子打字的,不是吗?!

    参考文献:

    Python: Bind an Unbound Method?

    In [6]: a = A.a.im_func.__get__(B(), B)
    
    In [7]: a
    Out[7]: <bound method B.a of <__main__.B instance at 0x7f37d81a1ea8>>
    
    In [8]: a(2)
    2
    

    裁判:

    一些ipython代码示例

    In [1]: class A():
        def a(self, a=0):
            print a
       ...:
    
    In [2]: A.a
    Out[2]: <unbound method A.a>
    
    In [3]: A.a.im_func
    Out[3]: <function __main__.a>
    
    In [4]: A.a(B())
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-4-7694121f3429> in <module>()
    ----> 1 A.a(B())
    
    TypeError: unbound method a() must be called with A instance as first argument (got B instance instead)
    

    python 3

    In [2]: class A():
        def a(self, a=0):
            print(a)
       ...:
    
    In [3]: def a():
       ...:     pass
       ...:
    
    In [4]: class B():
       ...:     pass
    
    In [5]: A.a(B())
    0
    
    In [6]: A.a
    Out[6]: <function __main__.A.a>
    
        4
  •  0
  •   Thilo    17 年前

    不久前,我想知道PerlMonks上Perl中的相同“功能”,以及 general consensus 当它工作时(就像在Python中一样),你不应该这样做。