Skip to content
Advertisement

Define and use class methods from variable

Let’s say I have two classes with some methods.

First class:

@dataclass
class MyFirstClass:
    y1: List[float]
    y2: List[float]
    
    @property
    def my_func1(self) -> List[float]:
        return self.y1-self.y2

    @property
    def my_func2(self) -> List[float]:
        return self.y1+self.y2

    @property
    def my_func3(self) -> List[float]:
        return self.y1*self.y2

Second class:

@dataclass
class MySecondClass:
    list_vals: List[float]
    
    @property
    def norm1(self):
        return self.list_vals
 
    @property
    def norm2(self):
        return self.list_vals / numpy.mean(self.list_vals)

So my question is two fold. Say in my main I have something like:

def main():
    FUNCTION = <?>
    NORM = <?>

    y1 = [1, 2, 3, 4, 5]
    y2 = [3, 4, 5, 6, 7]

    test = MyFirstClass(y1, y2).my_func1

Then I just call MyFirstClass with the y1 and y2 lists and get an output.

But as can be seen in the beginning of main I have FUNCTION and NORM. Is there any way to call MyFirstClass from there, and then reuse it all through main, i.e. something like:

FUNCTION = MyFirstClass.my_func1

test = FUNCTION(y1, y2)

This doesn’t work obviously. So how can one do that ?

Also, and this is probably a build upon the above, how can I, once again, choose the norm function to be used in the other class ? For instance, if I update MyFirstClass a bit to:

@dataclass
    class MyFirstClassUpdated:
        y1: List[float]
        y2: List[float]
        norm: NORM
        
        @property
        def my_func1(self) -> List[float]:
            return norm(self.y1)-norm(self.y2)
    
        @property
        def my_func2(self) -> List[float]:
            return norm(self.y1)+norm(self.y2)
    
        @property
        def my_func3(self) -> List[float]:
            return norm(self.y1)*norm(self.y2) 

And then when the class is called it takes the NORM argument from the main function, i.e. something like:

FUNCTION = MyFirstClass.func1
NORM = MySecondClass.norm1

test = FUNCTION(y1, y2, NORM)

I have no idea if this is even possible without making the code “uglier”.

Advertisement

Answer

You need to create an instance of MyFirstClass, and pass it as the self argument to the function.

FUNCTION = MyFirstClass.my_func1
mfc = MyFirstClass(y1, y2)
test = FUNCTION(mfc)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement