Python,从类\u A调用类\u B,从类\u A继承方法

2024-04-23 16:38:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有主.py,父类,类A和类B在4个不同的文件中。你知道吗

从主.py我调用类\u A(parentClass的子类),从类\u A中我需要调用类\u B,其中我需要类\u A和parentClass的所有方法。我该怎么做?你知道吗

class parentClass(object):
    def __init__(self):
       ......

class class_A(parentClass):
   def __init__(self):
       super().__init__()

   def method1(self):
       ....

   def method2(self):
       ....

   def call_class_B(self)
       x = class_B()


class class_B(?):
   def __init__(self):
       ...
   here I need to call the method of the other classes

基本上,类\u B是类\u a的子类,但它是从类\u a调用的


Tags: 文件the方法pyselfobjectinitdef
1条回答
网友
1楼 · 发布于 2024-04-23 16:38:32

问题

我相信,根据你问题的第一行,这里的首要问题是避免circular import。如果这些类中的每一个都在一个单独的文件中,则很难确保在需要时以及如何定义正确的父类。你知道吗

解决方案

解决这个问题的一个方法是将整个过程设置为一个模块(在一个名为myu module的目录中),其中包含以下文件:

\uuuu初始\uuuuuuuy.py:

from .parent import Parent

class ClassB(object):
    pass

from .a import ClassA
from .b import ClassB

你知道吗父.py你知道吗

class Parent(object):
    def meth(self):
        print("From Parent")

a.py公司

import my_module

class ClassA(my_module.Parent):
    def get_a_B(self):
        return my_module.ClassB()

    def meth(self):
        super().meth()
        print("From ClassA")

b.py公司

import my_module

class ClassB(my_module.ClassA):

    def meth(self):
        super().meth()
        print("From ClassB")

那么,在我的教学单元之外,你可以有以下内容主.py地址:

from my_module.b import ClassB

if __name__ == "__main__":
    myB = ClassB()
    my_other_B = myB.get_a_B()
    my_other_B.meth()

在运行(Python 3.5)时,它将打印以下输出:

From Parent
From ClassA
From ClassB

怎么回事?你知道吗

在模块的__init__文件中,我们声明了ClassB的“虚拟”版本。我们使用它来定义a.py中的ClassA,但是在我们实际使用ClassA之前,它已经被b.py中定义的ClassB所取代,从而给出了我们所期望的行为。你知道吗

更好的解决方案

不过,所有这些都有点像code smell。如果类a和类B真的紧密地结合在一起,那么它们有可能是一个单独的类。至少,它们应该在同一个文件中定义,正如zwer所指出的那样,该文件可以正常工作。你知道吗

或者,您可以考虑包装父类和ClassA的一些功能,而不是继承,但是我们可能需要更多关于您正在做什么的信息来说明最佳解决方案是什么。你知道吗

相关问题 更多 >