'Usage of __setattr__ to rewrite whole method of library class issue: missing 1 required positional argument: 'self'

I've got some imported packages with tricky structure and need to call some method that bases on lots of other methods with non-default parameters, which are not class attributes themself like pipeline in sklearn.

Minimal example of this module structure:

class Library_class:
    def __init__(
        self,
        defined_class_options,
      ):
        self.defined_class_options = defined_class_options
        
    def method1( self , default_non_class_arg = 12 ):
        
        assert self.defined_class_options==3
        return default_non_class_arg
        
    def method2( self, image ):
        return image/ self.method1()

Default usage:

    class_instance = Library_class( 3 )
    class_instance.method2( 36 )
> 3.0

I need to set default_non_class_arg to 6 for example.

I've tried multiple approaches:

  1. Analogous to https://stackoverflow.com/a/35634198/7607734
    class_instance.method2( 36 ,
                 method1__default_non_class_arg=3  )

TypeError: method2() got an unexpected keyword argument 'method1__default_non_class_arg'

It don't work probably because class definitely don't have set_params

  1. With setattr on redefined function
    class_instance.__setattr__('method1',Library_class.new_method1)
    class_instance.method2( 36 )

TypeError: new_method1() missing 1 required positional argument: 'self'



Sources

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

Source: Stack Overflow

Solution Source