将变量设置为类的类型

时间:2018-02-12 01:45:25

标签: python-3.x class instance declaration

我试图找出如何将变量作为Python 3中类的声明类型(对象)传递。

示例:

#class defintion
class TestClass(Document):
    test = IntField()

me = MongoEngine(app)
testInstance = TestClass(me.Document) # How do i pass the Document variable

我尝试将MongoEngine变量的实例作为变量传递给TestClass,但这不能正常工作吗?

1 个答案:

答案 0 :(得分:1)

我认为你需要将你的课程结构略有不同。不要将Document放在类定义中,就像TestClassDocument的子类一样。相反,将类声明为标准(object),并定义一个__init__,您可以在其中传递一个变量,该变量可以在启动后由类的实例使用:

class TestClass(object):

    def __init__(self, my_document):
        self.document = my_document
        # at this point  the self.document variable
        # is the same as the variable passed
        # when initiating the instance of the class

    def show_document(self):
        # do something with your document
        print(self.document)

me = MongoEngine(app)

# this will call __init__() passing the variable
test_instance = TestClass(me.Document)

# now do something with the class intance
test_instance.show_document()

[根据评论编辑]

OP的评论:

  

查看type(test_instance),它与a不同   MongoEngine.Document。我希望创建一个类型' Document'   并传入该类型的实例?

您可以创建将父类作为类定义中的对象的类。我不知道MongoEngine我将以list

为例

如下定义的类,其行为与list完全相同,但如果您执行type(),则会返回MyList

class MyList(list):

    def __init__(self, *args, **kwargs):
        super(MyList, self).__init__(*args, **kwargs)

    def my_extra_function(self):
        print('hello world')

使用此课程时,您可以轻松看到这一点,首先将其视为list

my_instance = MyList([1, 2, 3])

print(my_instance)
print(my_instance[::-1])

这将表现得好像是list

但是当您执行type()时,它不会返回与list相同的内容:

print(type(list))
print(type(list()))
print(type(MyList()))
print(type(my_instance))

输出:

<class 'type'>
<class 'list'>
<class '__main__.MyList'>
<class '__main__.MyList'>

因此,即使您尝试创建一个以MongoEngine.Document为父对象的类,type()仍会显示您自己定义的类。

class MyClass(MongoEngine.Document):

    def __init__(self, *args, **kwargs):
        super(MyClass, self).__init__(*args, **kwargs)

my_instance = MyClass('something')

如果您执行type(my_instance),它将返回您的自定义类,而不是父对象类型。

不确定MongoEngine是如何工作的,如果你真的可以这样做,那么YMMV。

您可以通过在我的示例类中执行以下操作来更改正在返回的名称type()。在self.__class__中设置__init__()。像这样:

class MyList(list):

    def __init__(self, *args, **kwargs):
        super(MyList, self).__init__(*args, **kwargs)
        self.__class__ = type('list', (list,),{})

    def my_extra_function(self):
        print('hello world', self)

my_instance = MyList([1, 2, 3])

print(type(list))
print(type(list()))
print(type(MyList()))
print(type(my_instance))

输出:

<class 'type'>
<class 'list'>
<class '__main__.list'>
<class '__main__.list'>

如果这个技巧适用于MongoEngine.Document,我不知道。

相关问题