vendredi 27 février 2015

What is the best way to perhaps call a function, every time, inside a class?

I have a class that has an optional function as a parameter. Sometimes I create instances of this class with a function, sometimes not.


The function is called every time when some methods of the instance are called. Of course if the function was not given, nothing happens there.


My question is, what is the best way to achieve this ? I tried a couple of things. Can you judge my solutions, by performance, scalability and readability ? Do you have better solutions ?


The class looks like this



class MyClass(...):
def __init__(self, function=None):
self.function = function

def method_a(self, ...)
...
self.function(a,b,c)
...

def method_b(self, ...)
...
self.function(a,b,c)
...

def method_c(self, ...)
...
#not every method bothers with the function
...


Of course this produces



TypeError: 'NoneType' object is not callable


The most naive solution is to change the class itself with defensive ifs or trials:



class MyClass(...):
def __init__(self, function=None):
self.function = function

def method_a(self, ...)
...
if self.function:
self.function(a,b,c)
...

def method_b(self, ...)
...
if self.function:
self.function(a,b,c)
...


second solution is to create a do nothing function and perhaps store it in self.function:



def do_nothing(*x):
pass

class MyClass(...):
def __init__(self, function=None):
if function is None:
function = do_nothing
self.function = function

def method_a(self, ...)
...
self.function(a,b,c)
...

def method_b(self, ...)
...
self.function(a,b,c)
...


the third solution is to create a function wrapper with defensive ifs inside it:



class Maybe(object):
def __init__(self, function=None):
self.function = function

def __call__(self, *args):
if self.function is None:
return
# else
return self.function(args)

class MyClass(...):
def __init__(self, function=None):
self.function = Maybe(function)

def method_a(self, ...)
...
self.function(a,b,c)
...

def method_b(self, ...)
...
self.function(a,b,c)
...

Aucun commentaire:

Enregistrer un commentaire