I am trying to figure out how I can pass a variable as the declaration type (object) for a class in Python 3.
Example:
#class defintion
class TestClass(Document):
test = IntField()
me = MongoEngine(app)
testInstance = TestClass(me.Document) # How do i pass the Document variable
I tried passing an instance of the MongoEngine
variable as a variable to the TestClass
but this isn't working properly?
I think you need to structure your class slightly different. Don't put
Document
in the class definition as if theTestClass
is a subclass ofDocument
. In stead, declare the class as standard(object)
, and define an__init__
where you can pass a variable which can be used by the instance of the class after initiation:[EDIT based on comment]
OP's comment:
You can create classes which would take a parent class as object in the class definition. As I do not know
MongoEngine
I will make an example withlist
A class defined as follows, will behave perfectly like a
list
, but if you do atype()
it will come back asMyList
:You can easily see this when using this class, first look at it as a
list
:this will behave as if it was a
list
.But when you do a
type()
, it will not return the same aslist
:output:
So even when you try to create a class with the
MongoEngine.Document
as parent object, thetype()
will still show you your own defined class.If you do a
type(my_instance)
it will return your custom class, and not the parent object type.Not sure how MongoEngine works, and if you can actually do something like this, so YMMV.
You can change the name
type()
is returning, by doing the following in my example class. Setting theself.__class__
in the__init__()
. Like this:output:
If this trick works for
MongoEngine.Document
I do not know.