gpt4 book ai didi

python-3.x - 在单独的文件中定义 Python 类

转载 作者:行者123 更新时间:2023-12-05 01:17:45 25 4
gpt4 key购买 nike

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

最佳答案

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

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

中使用的 class

同样基于 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

关于python-3.x - 在单独的文件中定义 Python 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48756404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com