Python: How can I separate functions of class into multiple files?

前端 未结 3 1439
我在风中等你
我在风中等你 2020-11-29 22:14

I know this has been asked a couple of times, but I couldn\'t quite understand the previous answers and/or I don\'t think the solution quite represents what I\'m shooting fo

3条回答
  •  萌比男神i
    2020-11-29 22:45

    Here is an implementation of @Martijn Pieters♦'s comment to use subclasses:

    main.py:

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

    separate.py:

    class BaseClass(object):
    
        # You almost always want to initialize instance variables in the `__init__` method.
        def __init__(self):
            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:
        #
        # Why are there "tons" of _similar_ functions?
        # Remember that functions can be defined to take a
        # variable number of/optional arguments, lists/tuples
        # as arguments, dicts as arguments, etc.
    

    from main import MainClass
    m = MainClass()
    m.func_1(1, 2)
    ....
    

提交回复
热议问题