方法分配和对象

时间:2009-09-15 06:09:53

标签: python

我遇到了python问题: 我想将一个方法分配给另一个类的对象,但是在这个方法中使用它自己的属性。因为我的项目中有许多不同使用方法的容器(不是那个例子)我不想使用继承,thad会强迫我为每个实例创建一个自定义类。

class container():
    def __init__(self):
        self.info = "undefiend info attribute"

    def use(self):
        print self.info


class tree():
    def __init__(self):

        # create container instance
        b = container()

        # change b's info attribute
        b.info = "b's info attribute"

        # bound method test is set as use of b and in this case unbound, i think
        b.use = self.test

        # should read b's info attribute and print it
        # should output: test: b's info attribute but test is bound in some way to the tree object
        print b.use()

    # bound method test
    def test(self):
        return "test: "+self.info


if __name__ == "__main__":
    b = tree()

非常感谢您阅读本文,也许可以帮助我! :)

4 个答案:

答案 0 :(得分:2)

你走了。你应该知道self.test已经绑定了,因为你在__init__时已经创建了实例并绑定了它的方法。因此,您必须使用im_func成员访问未绑定的成员,并使用MethodType绑定它。

import types

class container():
    def __init__(self):
        self.info = "undefiend info attribute"

    def use(self):
        print self.info


class tree():
    def __init__(self):

        # create container instance
        b = container()

        # change b's info attribute
        b.info = "b's info attribute"

        # bound method test is set as use of b and in this case unbound, i think
        b.use = types.MethodType(self.test.im_func, b, b.__class__)

        # should read b's info attribute and print it
        # should output: test: b's info attribute but test is bound in some way to the tree object
        print b.use()

    # bound method test
    def test(self):
        return "test: "+self.info


if __name__ == "__main__":
    b = tree()

答案 1 :(得分:1)

看起来你正在尝试使用继承?树继承自容器?

答案 2 :(得分:1)

使用tree.test而不是self.test。实例的方法属性绑定到该实例。

答案 3 :(得分:1)

不要动态移动方法。

使用委派。避免魔术。

将“Tree”对象传递给Container。它可以节省尝试移动方法。

class Container( object ):
    def use( self, context ):
        print context.info
        context.test()

class Tree( object ):
    def __init__( self, theContainerToUse ):
        b= theContinerToUse( self )
        print b.use()
    def test( self ):
        print "test"+self.info