在单独的文件中定义 Python class

Define Python class in separate file

# File 1
me = MongoEngine(app) # I want to use my instance of MongoEngine to define new classes like the example in File 2

# File 2
class Book(me.Document):
    title = StringField(null=False, unique=True)
    year_published = IntField(null=True)

如何在新文件中创建新 类 时将实例 me.Document 作为对象定义传递。如果我将它们放在同一个文件中,它会起作用吗?

File 2 中执行 me 对象的导入:

from file1 import me


class Book(me.Document):
    pass
    # ...

就像文件中的任何 Python 对象一样,可以导入 me。你可以这样做:

import file1
class Book(file1.me.Document):
    #Do what you want here!

希望对您有所帮助!

我认为选择的答案不完全正确。

看来File1.py是你执行的主脚本, File2.py 是一个模块,其中包含您希望在 File1.py

中使用的 class

同样基于我想建议如下结构:

File1.py 和 File2.py 位于同一目录中

File1.py

import MongoEngine
from File2 import Book

me = MongoEngine(app)

# according to the documentation
# you do need to pass args/values in the following line
my_book = Book(me.Document(*args, **values))
# then do something with my_book
# which is now an instance of the File2.py class Book

File2.py

import MongoEngine

class Book(MongoEngine.Document):

    def __init__(self, *args, **kwargs):
        super(Book, self).__init__(*args, **kwargs)
        # you can add additional code here if needed

    def my_additional_function(self):
        #do something
        return True