[英]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
放在類定義中,就好像TestClass
是Document
的子類一樣。 相反,將類聲明為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.