如何从动态导入的类中调用方法

时间:2013-12-01 13:15:47

标签: python class

这种动态导入A类中的B类

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

在班级B里面我有:

class ClassB:

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

我想在B类中调用A类的方法'randomword',我该怎么办?

1 个答案:

答案 0 :(得分:1)

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

输出类似于以下内容的内容:

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"

或者,您可以将self变量(ClassA)传递给ClassB的 init 函数,然后将其分配给另一个变量:

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

输出:

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

希望这有帮助。