将一个类的实例方法绑定到另一个类

问题描述

考虑以下情况:

class test:
  def foo(self,o):
    print(o)

  @staticmethod
  def bar(o):
    print(o)
    
  @classmethod
  def qux(cls,o):
    print(cls)
    print(o)

def baz(o):
  print(o)

t = test()

class A:
  meth1 = t.bar
  meth2 = t.foo
  meth3 = baz
  meth4 = t.qux

a = A()
a.meth1()
a.meth3()
# a.meth4()
# a.meth2()

这很好用,但如果我调用 meth2/4,我会收到以下错误

TypeError: <foo/qux>() missing 1 required positional argument: 'o'

有什么办法可以让 t.foot.quxt.barbaz 一样工作吗?

解决方法

meth4 中的

A 在这里不被视为类方法,因为您还没有这样定义它。

类方法使用装饰器语法声明,如下所示:

@decorator
def func(x,y):
    return z

本质上定义了一个函数 func,然后对其调用 decorator

因此,您实际上可以只执行 meth4 = classmethod(t.qux),而且效果很好。

对于meth2,我不确定您预期会发生什么。它是一个实例方法,它隐式地接受self并接受一个参数o,所以当你调用a.meth2时,当然需要指定一个参数o