繁体   English   中英

将变量设置为类的类型

[英]Set variable as type of class

我试图弄清楚如何将变量作为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但这不能正常工作?

我认为您需要在课程结构上稍有不同。 不要将Document放在类定义中,就好像TestClassDocument的子类一样。 相反,将类声明为standard (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) ,它与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()返回的名称。 __init__()设置self.__class__ 像这样:

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有效,我不知道。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM