Subclass a Python class with predefined parameters in one liner

132 Views Asked by At

Given a simple class:

class MyClassA():
    def __init__(self, param_a, param_b):
        
        self.param_a = param_a
        self.param_b = param_b

    def my_method(self, param_c):
        return some_fun(self.param_a, self.param_b)

Now I want to create an instance of this class with just param_b being set. Namely something like:

class MyClassB(MyClassA):
    def __init__(self, param_a):
        
        super().__init__(param_a, something)

Now I want: my_obj_c = MyClassB(some_val).

The question, is there a way to get my_obj_c in one liner without explicitly building MyClassB?

Motivation

The reason I need this is actually this class is used by a different procedure which supports calling the class with a single input.
What I want is to try it (like grid search) which many different values of param_b. This is why setting a default value won't do it.

2

There are 2 best solutions below

1
Tourelou On

What do you think about

class MyClassA():
    def __init__(self, param_a, param_b=SomeValue):
...

this way you can create instance like this:

obj1 = MyClassA(param_a, param_b)
obj2 = MyClassA(param_a)

In the second instance the param_b will be someValue

2
Mark On

You could use functools.partial to make a partial of the class constructor with the second argument pre-set.

import functools 

class MyClassA():
    def __init__(self, param_a, param_b):        
        self.param_a = param_a
        self.param_b = param_b

    def my_method(self):
        return f"{self.param_a} {self.param_b}"

Paramterized = functools.partial(MyClassA, param_b="world")

my_instance = Paramterized("hello")
# <__main__.MyClassA at 0x112816e00> 
my_instance.my_method()
#'hello world'

my_instance2 = Paramterized("goodbye cruel")
my_instance2.my_method()
# 'goodbye cruel world'