gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:42:01 26 4
gpt4 key购买 nike

动态导入类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方法,该怎么办?

最佳答案

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"
<小时/>

希望这有帮助。

关于python - 如何从动态导入的类中调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20312503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com