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

前端 未结 3 1459
我在风中等你
我在风中等你 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条回答
  •  甜味超标
    2020-11-29 22:38

    I use the approach I found here It shows many different approaches, but if you scroll down to the end it the preferred method is to basically go the opposite direction of @Martin Pieter's suggestion which is have a base class that inherits other classes with your methods in those classes.

    so folder structure something like:

    _DataStore/
        __init__.py
        DataStore.py
        _DataStore.py
    
    

    So your base class would be:

    # DataStore.py
    
    import _DataStore
    
    class DataStore(_DataStore.Mixin): # Could inherit many more mixins
    
        def __init__(self):
            self._a = 1
            self._b = 2
            self._c = 3
    
        def small_method(self):
            return self._a
    
    

    Then your Mixin class:

    # _DataStore.py
    
    class Mixin:
    
        def big_method(self):
            return self._b
    
        def huge_method(self):
            return self._c
    

    Your separate methods would be located in other appropriately named files, in this example it is just _DataStore.

    I am interested to hear what others think about this approach, I showed it to someone at work and they were scared by it, but it seemed to be a clean and easy way to separate a class into multiple files.

提交回复
热议问题