在课堂上发起多个课堂

时间:2018-11-20 08:59:14

标签: python class

我在多个文件中有多个班级。例如,

文件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,否则,我将能够同时使用gen_list_spice和{ {1}}当我只需要调用对象gen_postsim

1 个答案:

答案 0 :(得分:0)

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

文件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()
相关问题