简体   繁体   中英

Why cannot I import a .py file to another within the same directory?

I have the following 4 python files within the folder SubFolder , assembled as such:

   CodeFolder
       SubFolder
           GeneticAlgorithm.py
           main.py
           heuristic1.py
           heuristic2.py

I am trying to import the file GeneticAlgorithm.py within my main.py file, using the import statement at the beginning of the class:

import GeneticAlgorithm

The problem: PyCharm is highlighting this and says " no module named GA ".

Any clues as to what may be causing this issue and how to solve it? Thank you!

Correct me if I'm wrong but you might not have GA module in your GeneticAlgorithm.py

If you do, then you can do similar to below:

Similar to your folder structure:

在此处输入图像描述

From main.py call GeneticAlgorithm.py. For example:

from GeneticAlgorithm import GA


def main():
    ga_obj = GA(mutation_rate=0.5)
    print("Call GA module")
    

if __name__ == '__main__':
    main()

If we look at the GeneticAlgorithm.py

class GA:
    def __init__(self, mutation_rate):
        self.mutation = mutation_rate

We have GA class.

This is a simple demonstration of how you can use.

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