# 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
作为Object定义传递。如果我把它们放在同一个文件中,它可以工作吗?
答案 0 :(得分:1)
在File 2
执行me
对象的导入:
from file1 import me
class Book(me.Document):
pass
# ...
答案 1 :(得分:1)
就像文件中的任何Python对象一样,可以导入me
。你可以这样做:
import file1
class Book(file1.me.Document):
#Do what you want here!
希望我有所帮助!
答案 2 :(得分:1)
我认为答案选择答案并不完全正确。
似乎File1.py
是您执行的主要脚本,
File2.py
是一个模块,其中包含您希望在class
中使用的File1.py
同样基于previous question of the OP我想建议以下结构:
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