Purpose and method objects

I have a python problem: I want to assign a method to an object of another class, but this method uses its own attributes. Since I have many containers with different usage methods in my project (not in this example), I do not want to use inheritance, thad will force me to create my own 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 info attribute
        b.info = "b 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 info attribute and print it
        # should output: test: b 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()

Thanks for reading this, and maybe helping me! :)

+3
source share
4 answers

Here you go. You should know that self.test is already bound, because by the time you are in __init__, the instance is already created and its methods are bound. Therefore, you must access the unrelated member using the im_func member and bind it to the MethodType method.

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 info attribute
        b.info = "b 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 info attribute and print it
        # should output: test: b 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()
+2

, ? ?

+1

Use tree.test instead of self.test. The attributes of an instance method are bound to this instance.

+1
source

Do not move methods dynamically.

Just use delegation. Avoid magic.

Pass the Tree object to the Container. It saves an attempt to move methods.

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
+1
source

Source: https://habr.com/ru/post/1717707/


All Articles