Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define Python class in separate file

# 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)

How can i pass the instance me.Document as an Object definition when creating my new classes in a new file. It works if i put them in the same file?

like image 481
Warz Avatar asked May 20 '26 04:05

Warz


2 Answers

I believe that the answer choosen as answer is not fully correct.

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

Also based on a previous question of the OP I would like to suggest the following structure:

File1.py and File2.py are located in the same direcory

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
like image 63
Edwin van Mierlo Avatar answered May 21 '26 17:05

Edwin van Mierlo


In File 2 perform import of the me object:

from file1 import me


class Book(me.Document):
    pass
    # ...
like image 28
Alex Bausk Avatar answered May 21 '26 18:05

Alex Bausk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!