Search code examples
pythonoopmethods

How to define just a method of a class in a separate file?


I was coding a class with a big method, which I tried to move into a separate file. My idea was:

class Game(object):
    def __init__(self):
        pass
    import funcFile

instance = Game()
instance.func()

While in funcFile.py:

def func():
    print("Hello world!")

But I got this error:

Traceback (most recent call last):
    instance.func()
TypeError: 'module' object is not callable

Is there a nice way to do this, or should I put everything in one file?


Solution

  • There are many ways to solve this kind of problem.

    The most straightforward solution (which is what I think you had in mind) is to factor out the implementation of the func method to a separate module. But you still need to define the method in the class.

    main.py:

    from func_module import func_implementation
    
    class Game:  # note: you don't need (object)
        def __init__(self):
            pass
    
        def func(self):
            return func_implementation()
    
    instance = Game()
    instance.func()
    

    func_module.py:

    def func_implementation():
        print('hello')
    

    Another approach would be to factor out the func method to another class which the Game class inherits. This pattern is also known as a mixin class:

    main.py:

    from func_module import FuncMixin
    
    class Game(FuncMixin):
        def __init__(self):
            pass
    
    instance = Game()
    instance.func()
    

    func_module.py:

    class FuncMixin:
        def func(self):
            print('hello')
    

    But this is less clear, as you can't immediately see that the Game class has a func method and what it does. Also you can introduce subtle bugs with multiple inheritance if you're not careful. So in your case I'd prefer the first approach.