Injecting methods into instance / class
duncan smith
duncan at invalid.invalid
Sun Dec 2 14:59:04 EST 2018
On 02/12/2018 18:26, Stefan Ram wrote:
> duncan smith <duncan at invalid.invalid> writes:
>> I have tried to find examples of injecting methods into classes without
>
> Wouldn't the normal approach be to just define a
> class with your functions as instance methods?
>
> main.py
>
> class C():
> def __init__( self, value=0 ):
> self.value = value
> def __sub__( self, other ):
> return C( self.value - other.value )
> def __str__( self ):
> return 'C '+ str( self.value )
> def yourfunctionhere( self ):
> pass
>
> c = C(); c.value = 22
> d = C(); d.value = 27
> print( d - c )
>
> transcript
>
> C 5
>
What I'm trying to avoid is,
def __sub__(self, other):
return subtract(self, other)
def __add__(self, other):
return add(self, other)
def __mul__(self, other):
return multiply(self, other)
def some_func(self, *args, **kwargs):
return some_func(self, *args, **kwargs)
for many existing functions. Injecting them as instance methods was
probably not ideal, but I could get it working (apart from the special
methods). Ideally I'd like to take all the functions defined in a
separate module, create ordinary class methods from most of them (with
the same name), then create special methods from the remaining
functions. Cheers.
Duncan
More information about the Python-list
mailing list