Jupyter - Split classes in several cells

I wonder if it is possible to split jupyter classes into different cells? Let's say:


#first cell:
class foo(object):
    def __init__(self, var):
        self.var = var

#second cell
    def print_var(self):
       print(self.var)

For more complex classes, it’s really annoying to write them in one cell. I would like to put each method in a different cell.

Someone did this last year, but I'm wondering if there is anything in the assembly, so I don't need external scripts / imports.

And if not, I would like to know if there is a reason not to give the opportunity to split your code and document / debug it easier.

Thanks in advance

+4
source share
3 answers

, ... , , :


# First cell
class Foo(object):
    pass

# Other cell
def __init__(self, var):
    self.var = var

Foo.__init__ = __init__

# Yet another cell
def print_var(self):
   print(self.var)
Foo.print_var = print_var

, , ... .

EDIT: , , . , , , "" . , (?), , .

. ( - , ), , , , .

" " .

"" . ... , (ab) ,

+4

Github " Python # 1243", : https://github.com/jupyter/notebook/issues/1243

, , jdc - Jupyter. , , URL- https://alexhagen.imtqy.com/jdc/

Doug Blank Python, - :

1:

class MyClass():
    def method1(self):
        print("method1")

2:

class MyClass(MyClass):
    def method2(self):
        print("method2")

3:

instance = MyClass()
instance.method1()
instance.method2()

Jupyter Notebook, VS Code, , , pylint [pylint] E0102:class already defined line 5 VS Code, , . , VS Code .

+1

It is not possible to split a single class. However, you can dynamically add methods to an instance of this object

CELL No. 1

import types
class A:
    def __init__(self, var):
        self.var = var

a = A()

And in another cell:

CELL # 2

def print_var(self):
    print (self.var)
a.print_var = types.MethodType( print_var, a )

Now this should work:

CELL No. 3

a.print_var()
0
source

Source: https://habr.com/ru/post/1681671/


All Articles