Use a class in the context of a different module

后端 未结 7 1499
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 08:53

I want to modify some classes in the standard library to use a different set of globals the ones that other classes in that module use.

Example

This exampl

7条回答
  •  -上瘾入骨i
    2021-01-12 09:27

    If you use Python 3, you can subclass B and redefine the __globals__ attribute of the __init__ method like this:

    from module_a import B
    
    function = type(lambda: 0)  # similar to 'from types import FunctionType as function', but faster
    my_global = []
    
    
    class My_B (B):
        __init__ = function(B.__init__.__code__, globals(), '__init__',  B.__init__.__defaults__, B.__init__.__closure__)
    

提交回复
热议问题