在单独的文件中定义 Python 类

War*_*arz 3 oop abstraction instance-variables python-3.x

# 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)
Run Code Online (Sandbox Code Playgroud)

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

Edw*_*rlo 5

我相信选择的答案并不完全正确。

看来这File1.py是您执行的主脚本,并且是一个包含您希望使用的File2.py模块classFile1.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
Run Code Online (Sandbox Code Playgroud)

文件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
Run Code Online (Sandbox Code Playgroud)