在课堂上发起多个课堂

2024-10-04 11:36:21 发布

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

我在多个文件中有多个类。例如

文件1:

class gen_list ():
  def gen_list_spice(self):
    ...

文件2:

class gen_postsim ():
  def gen_postsim(self):
    ...

我想用另一个类似这样的类来包装它

class char ()
   def __init__ (self, type):
     if (type == list):    
       ....... (load gen_list only<-- this part i do not know how to write)
     else 
       ....... (load both)

在顶部包装中,我想举例来说,如果我给出list,我将能够使用gen_list_spice,否则,当我只需要调用对象char时,我将能够同时使用gen_list_spicegen_postsim


Tags: 文件selfonlyifinitdeftypeload
1条回答
网友
1楼 · 发布于 2024-10-04 11:36:21

我不知道你为什么这样做,但你可以导入文件的任何部分。你知道吗

文件1应命名为get_list.py

class ListGenerator():

    def gen_list_spice(self):
        pass

文件2应命名为gen_postsim.py

class PostsimGenerator():

    def gen_postsim(self):
        pass

在包装文件中:

class char():

    def __init__(self, type):
        if type == list:
            from gen_list import ListGenerator
            gl = ListGenerator()
            gl.gen_list_spice()
        else:
            from gen_postsim import PostsimGenerator
            from gen_list import ListGenerator
            gp = PostsimGenerator()
            gp.gen_postsim()

但这不是一个好的做法。您可以使用函数而不是类,并在文件头中导入它们。你知道吗

在文件gen_list.py

def gen_list_spice():
    print("get list")
    pass

在文件gen_postsim.py

def gen_postsim():
    print("gen postsim")
    pass

在包装文件中

from gen_list import gen_list_spice
from gen_postsim import gen_postsim

class char():

    def __init__(self, type):
        if type == list:
            gen_list_spice()
        else:
            gen_list_spice()
            gen_postsim()

相关问题 更多 >