'Splitting class functions across multiple cells in Jupyter?

Given the following code:

class DTC:
    def __init__(self):
        self.__root = None

    def unique(self,Y):
        d = {}
        for i in Y:
            if i not in d:
                d[i]=1
            else:
                d[i]+=1
        return d

    def ent(self,Y):
        freq = self.__count_unique(Y)
        ent_ = 0
        total = len(Y)
        for i in freq:
            p = freq[i]/total
            entropy_ += (-p)*math.log2(p)
        return ent_

The above will run if it is place in a single cell in Jupyter Notebook. However, how can I make the class code work if I want it to be split into multiple cells like this:

Cell 1

class DTC:
    def __init__(self):
        self.__root = None

Cell 2

    def unique(self,Y):
        d = {}
        for i in Y:
            if i not in d:
                d[i]=1
            else:
                d[i]+=1
        return d

Cell 3

    def ent(self,Y):
        freq = self.__unique(Y)
        ent_ = 0
        total = len(Y)
        for i in freq:
            p = freq[i]/total
            ent_ += (-p)*math.log2(p)
        return ent_


Solution 1:[1]

A python-only solution:

class OutsourceMethods:
    @classmethod
    def method(cls, f):
        setattr(cls, f.__name__, f)
        

Used as:

class A(SuperA, OutsourceMethods):
    def __init__(self):
        self.x = 10


@A.method
def bar(self, y):
    print(self.x, y)

a = A()

a.bar(20)

> 10 20

b = A()
b.x = 3
b.bar() 

> 3 20

It's not 100% equivalent, but I haven't noticed a different so far.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nearoo