在单独的文件中定义 Python 类

新手上路,请多包涵
# 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 作为对象定义传递。如果我将它们放在同一个文件中,它会起作用吗?

原文由 Warz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 658
2 个回答

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

It seems that File1.py is your main script which is executed , and File2.py is a module which contains a class you wish to use in File1.py

同样基于 OP 的先前问题, 我想建议以下结构:

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

文件1.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

文件2.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

原文由 Edwin van Mierlo 发布,翻译遵循 CC BY-SA 3.0 许可协议

File 2 执行导入 me 对象:

 from file1 import me

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

原文由 Alex Bausk 发布,翻译遵循 CC BY-SA 3.0 许可协议