简体   繁体   中英

how to call a method from a class imported dynamically

This import dynamically the class B inside the class A

lib = __import__(module_name)
class_ = getattr(lib, module_name)
theclass = class_()

Inside the class BI have:

class ClassB:

    def main(self):
        a = classA.randomword(10) #This is wrong
        print 'hello ' + str(a)

I want to call the method 'randomword' of the class A inside the class B, how can I do?

class ClassA:
    def __init__(self):
        # CREATE ClassB right here
        print 'self is an INSTANCE of ClassA, look: ' + repr(self)
        print 'self.__class__ is a TYPE OF THE INSTANCE of ClassA, see? ' \
                                            + repr(self.__class__)
        class ClassB(self.__class__):
            # ClassA is a base class, ClassB is a child class
            def __init__(self):
                pass

            def main(self):
                a = self.randomword(10)
                print 'hello, the output of ClassA.randomword is "'+str(a)+'"'

        # Instantiate ClassB
        class_b = ClassB()
        class_b.main()

    def randomword(self, num):
        print 'randomword was called'
        return 'hey there'

a = ClassA()

Outputs something similar to the following:

self is an INSTANCE of ClassA, look: <__main__.ClassA instance at 0x7fa4f78b05f0>
self.__class__ is a TYPE OF THE INSTANCE of ClassA, see? <class __main__.ClassA at 0x7fa4f78bb0b8>
randomword was called
hello, the output of ClassA.randomword is "hey there"

Alternatively you can pass self variable (ClassA) to init function of ClassB, then assign it to another variable:

class ClassA:
    def __init__(self):
        # Create or import ClassB right here
        class ClassB():
            # ClassA is a base class, ClassB is a child class
            # base argument is an internal object of the base class (ClassA)
            def __init__(self, base):
                # Assign it to the class variable for the further use
                self.base = base

            def main(self):
                # Use it here
                a = self.base.randomword(10)
                print 'hello, the output of ClassA.randomword is "' + str(a)+'"'

        # Instantiate ClassB
        class_b = ClassB(self)
        class_b.main()

    def randomword(self, num):
        print 'randomword was called'
        return 'hey there'

a = ClassA()

Output:

randomword was called
hello, the output of ClassA.randomword is "hey there"

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM