方法赋值和对象

3 投票
4 回答
1550 浏览
提问于 2025-04-15 14:20

我在使用Python的时候遇到了一个问题:我想把一个方法分配给另一个类的对象,但这个方法需要使用它自己类里的属性。因为在我的项目中有很多不同用途的容器(不是这个例子里的),我不想用继承,这样会让我为每个实例都创建一个自定义类。

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 个回答

1

用 tree.test 代替 self.test。一个实例的方法属性是和这个实例绑定在一起的。

1

看起来你是在尝试使用继承的概念?树是从容器中继承的吗?

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()

撰写回答