简体   繁体   中英

How to import function into a class from external file?

I am coding a simple game of tic-tac-toe. My function to check winning is too repetitive and big, so I want to put it into an external file. My idea is:

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

instance = Game()
instance.func()

While in funcFile.py is:

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

But:

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

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

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM