[Python] How can I separate the functions of a class into multiple files?

Discussão em 'Python' iniciado por Stack, Fevereiro 9, 2025.

  1. Stack

    Stack Membro Participativo

    I have a main class that has a ton of different functions in it. It's getting hard to manage. I'd like to be able to separate those functions into a separate file, but I'm finding it hard to come up with a good way to do so.

    Here's what I've done so far:

    File main.py


    import separate

    class MainClass(object):
    self.global_var_1 = ...
    self.global_var_2 = ...

    def func_1(self, x, y):
    ...
    def func_2(self, z):
    ...
    # tons of similar functions, and then the ones I moved out:

    def long_func_1(self, a, b):
    return separate.long_func_1(self, a, b)

    File separate.py


    def long_func_1(obj, a, b):
    if obj.global_var_1:
    ...
    obj.func_2(z)
    ...
    return ...
    # Lots of other similar functions that use info from MainClass


    I do this because if I do:

    obj_1 = MainClass()

    I want to be able to do:

    obj_1.long_func_1(a, b)

    instead of:

    separate.long_func_1(obj_1, a, b)

    I know this seems kind of nit-picky, but I want just about all of the code to start with obj_1., so there isn't confusion.

    Is there a better solution that what I'm currently doing? The only issues that I have with my current setup are:

    1. I have to change arguments for both instances of the function
    2. It seems needlessly repetitive

    Continue reading...

Compartilhe esta Página