如何在python中将另一个类的成员函数复制到myclass中?

bal*_*lki 8 python reflection

我有一个实用程序类,我想从中使用另一个类中的一个成员函数.我不想继承那个班级.我只想重用其他类的成员函数之一的代码.一种部分继承.

class HugeClass():
   def interestedFunc(self,arg1):
      doSomething(self.someMember1)
   def OtherFunctions(self):
      ...



class MyClass():
   def __init__(self):
      self.someMember1 = "myValue"
      self.interestedFunc = MagicFunc(HugeClass.interestedFunc)

c = MyClass()
print c.interestedFunc(arg)
Run Code Online (Sandbox Code Playgroud)

MagicFunc在python中有这样的吗?

Tom*_*cki 9

你可以做你想做的事,即:

class Foo(object):
    def foo(self):
        print self.a

class Bar(object):
    foo = Foo.__dict__['foo']

b = Bar()
b.a = 1
b.foo()
Run Code Online (Sandbox Code Playgroud)

但你确定这是个好主意吗?

  • 使用`foo = Foo.foo`在Py3中工作正常,其中"绑定"和"未绑定"方法之间的差异不再存在. (8认同)
  • @NiklasR:只有遵循*Marcin*建议才行,但是`Foo .__ dict __ ['foo']`应该可以正常工作:[link](http://ideone.com/B1riI) (4认同)
  • dict的引用是不必要的. (2认同)
  • 仍然没有必要引用`__dict__`的情况:`Foo.foo.im_func`同样适用,并且也适用于缺少`__dict__`属性的类。 (2认同)
  • `Foo.foo.im_func`是CPython特有的,可能无法在其他Python实现中使用。 (2认同)