简体   繁体   中英

How to create python classes in Jupyter Notebook

I've tried to created and use classes in jupyter notebook. But it seems it doesn't work And I've tried this :

def pxlocal(line, cell):
    ip = get_ipython()
    ip.run_cell_magic("px", line, cell)
    ip.run_cell(cell)
ip.register_magic_function(pxlocal, "cell")    

And in different cell:

%%pxlocal class MyClass(object):

But when I run those two cells it gave me this error:

ERROR:root:Cell magic `%%px` not found.
In [11]:

What am I doing wrong?

There is no problem with defining a class in a different cell. Just make sure you define the class in a cell that appears before the cell were you want to use it.

In Jupyter Notebooks you have to be very areful about usage of cells and positioning. Like in your case if you want to create any class and then use it. For that you have to specify cell definition in one cell and afterthat only you can use it's functionalties

You can sse this simple example-

class Boy():

def _init_(self, name):

    self.name = name

And now I use it -

boy1 = Boy(name='Jack')

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