Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从实例方法定义的Jupyter magic_Python_Methods_Jupyter Notebook_Python Decorators - Fatal编程技术网

Python 从实例方法定义的Jupyter magic

Python 从实例方法定义的Jupyter magic,python,methods,jupyter-notebook,python-decorators,Python,Methods,Jupyter Notebook,Python Decorators,我正在编写一个类,它在进程完成时向用户发送空闲消息。我认为提供Jupyter魔术会很有用,这样用户可以在执行单元格时收到通知 这个类已经提供了一个装饰器,所以我想我应该把一个单元格执行包装到一个装饰过的函数中 from IPython.core.magic import register_cell_magic from IPython import get_ipython import functools class MyClass(object): def decorate(se

我正在编写一个类,它在进程完成时向用户发送空闲消息。我认为提供Jupyter魔术会很有用,这样用户可以在执行单元格时收到通知

这个类已经提供了一个装饰器,所以我想我应该把一个单元格执行包装到一个装饰过的函数中

from IPython.core.magic import register_cell_magic
from IPython import get_ipython

import functools

class MyClass(object):

    def decorate(self, f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            r = f(*args, **kwargs)
            print('Send a message here!')
            return r
        return wrapped

    @register_cell_magic
    def magic(self, line, cell):
        ip = get_ipython()
        @self.decorate
        def f():
            return ip.run_cell(cell)
        return f()
那么我会:

obj = MyClass()

# ----- NEW CELL
%%obj.magic
'''do some stuff'''
但我明白了

>> UsageError: Cell magic `%%obj.magic` not found.
我发现魔术是以它的名字注册的(上图,
magic
),所以
%%magic
有效。但是,由于混合中没有
self
,因此所有的参数都是混乱的

我希望magic是一个实例方法,这样就可以使用config(在
\uuuu init\uuuu
中设置)。有没有办法做到这一点

以下是一些我不想实施的黑客解决方案,除非我真的必须这样做:

  • 将常规函数作为参数注册到实例中。我不想把那行代码添加到笔记本中,我想使用实例方法
  • 注册一个在运行中构造实例的常规函数

  • 这是我能想到的最好的办法,也是我不想做的事情中的第一件

    from IPython.core.magic import register_cell_magic
    from IPython import get_ipython
    
    import functools
    
    class MyClass(object):
    
        def decorate(self, f):
            @functools.wraps(f)
            def wrapped(*args, **kwargs):
                r = f(*args, **kwargs)
                print('Send a message here!')
                return r
            return wrapped
    
    
        def register_magic(self):
            @register_cell_magic
            def magic(line, cell):
                ip = get_ipython()
                @self.decorate
                def f():
                    return ip.run_cell(cell)
                return f()
    
    然后

    obj = MyClass()
    obj.register_magic()
    
    # ------
    %%magic
    ...