简体   繁体   中英

ipython : creating Class on the fly

Why this works:

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>

But when it is from module it doesnt??

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

The problems is that globals() returns the dictionary implementing the current module namespace. (see here )

new_class2 is defined in a different module, therefore it is modifying the globals of that module.

I see, so the solution is

In [10]: import maker

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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