在单独的文件中定义Python类

时间:2018-02-12 22:13:46

标签: python-3.x oop instance-variables abstraction

# 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定义传递。如果我把它们放在同一个文件中,它可以工作吗?

3 个答案:

答案 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