簡體   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