maximxls
maximxls

Reputation: 63

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?

Upvotes: 0

Views: 396

Answers (2)

nadapez
nadapez

Reputation: 2707

You should try from funcFile import func in your main file:

from funcFile import func

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

instance = Game()
instance.func()

Upvotes: 0

mkrieger1
mkrieger1

Reputation: 23150

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.

Upvotes: 2

Related Questions