簡體   English   中英

ipython:即時創建 Class

[英]ipython : creating Class on the fly

為什么這有效:

In [1]: def new_class(klass):
   ...:    globals()[klass] = type(klass, (object,), {})
   ...:    

In [2]: new_class('AA')

In [3]: AA()
Out[3]: <__main__.AA at 0x7f5629c5ddc0>

但是當它來自模塊時它不會??

In [4]: from maker import *

In [5]: new_class2??
Signature: new_class2(klass)
Docstring: <no docstring>
Source:   
def new_class2(klass):
        globals()[klass] = type(klass, (object,), {})
File:      /my/py38/seq2struct/lib/maker.py
Type:      function

In [6]: new_class2('AB')

In [7]: AB()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [7], in <cell line: 1>()
----> 1 AB()

NameError: name 'AB' is not defined

問題是globals()返回實現當前模塊命名空間的字典。 (見這里

new_class2在不同的模塊中定義,因此它正在修改該模塊的全局變量。

我明白了,所以解決方案是

In [10]: import maker

In [11]: maker.AB()
Out[11]: <maker.AB at 0x7f5629bbe370>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM