Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method assignment and objects

Tags:

python

i've got a problem with python: I want to assign a method to an object form another class, but in this method use its own attributes. Since i have many container with different use methods in my project (not in that example) i dont want to use inheritance, thad would force me to create a custom class for each instance.

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

Thank you very much for reading this, and perhaps helping me! :)

like image 296
blackforestcowboy Avatar asked Feb 22 '26 08:02

blackforestcowboy


1 Answers

Here you go. You should know that self.test is already bound since by the time you are in __init__ the instance has already been created and its methods are bound. Therefore you must access the unbound member by using the im_func member, and binding it with 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()
like image 113
Unknown Avatar answered Feb 23 '26 20:02

Unknown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!