Working with multiple code files and folders in Py

2019-03-18 15:33发布

问题:

I am new to Python and I haven't figured out a simple way of separating code in multiple code files and folders.

What I do today is: for each folder I create an __init__.py file. Sometimes it's empty. I don't know why I do it, but it seems necessary. That's the first difference from working with C#.

The second difference is that for any file to reference any another I must use an import, like from model.table import Table. And if I have multiple references I need to use multiple imports:

from model import table1,table2

and then in the rest of the code I must use table1.Table1 per example. If I don't want to, I should

from model.table1 import Table1
from model.table2 import Table2

and then I can use simply Table1

That differs too much from what I'm used to in C#, where if all files were in the same namespace, we didn't have to import. Is there a simpler way for me?

回答1:

You should read up on modules: http://docs.python.org/tutorial/modules.html

Basically, I think you aren't organizing your code right. With python, directories and files have a meaning; it's not just what you write into the files. With every new directory (with __init__.py) and every new file you create a new "namespace"...

If you have the file /mydatabase/model.py and the Table1, Table2, etc defined in that model.py file you can simply:

from mydatabase.model import *

Do not create a new file for each Table class!



回答2:

The python import system is fairly similar to C#'s namespaces from what I understand of it. You can customize import behavior of modules in __init__.py if you really want to. You can also use import * or from x import * to pull all public objects defined by a module into your current namespace.

Consider in C#:

using System;
Console.WriteLine("hello world!");

In python, you could do (using this completely contrived situation):

system/
system/__init__.py
system/console.py

In __init__.py:

import console

In system/console.py:

import sys

def write_line(s):
    sys.stdout.write(s)

Now in your python code you could do:

from system import *
console.write_line('hello world!')

This is not generally considered a good idea in Python, however. For a bit more detail and good recommendations, check out this article: http://effbot.org/zone/import-confusion.htm



标签: python import