This is kind of an odd question. I have written a few classes that use reflection to find methods to execute on a given object.
For example, I have a class that calls methods based on the type
of data it encounters. The methods are user-defined, but it's just a nicer interface for making these kinds of modifications(turning all of one type
into another etc).
Here is what the class looks like:
class TypeWare(object):
def modify(self, data_set):
""" Iterate over data_set, find child class methods and execute them on the appropriate data type. """
types = [str, float, int, tuple, dict, list]
data_output = []
for data in data_set:
data_type = type(data)
if data_type in types:
try:
# Try to find the method by name.
method = getattr(self, data_type.__name__)
# Make modifications to data and add it to the output
data_output.append(method(data))
except AttributeError:
data_output.append(data)
else:
data_output.append(data)
return data_output
So any other class could just inherit this, and so long as it has methods named after the type
of data it should modify, that method would be called on that data type and the returned value would replace the original value.
Here is a simple example of what that would look like if my explanation is confusing:
class ExampleTypeWare(TypeWare):
# Square any integers
def int(self, value):
return value * value
# Operate recursively on lists.
def list(self, the_list):
return self.modify(the_list)
# Then the instance calls the modify method from the parent class.
tw = ExampleTypeWare()
print tw.modify([2, 4, 6, 8, [10, 12, 14]])
I guess my question is, is there a name for classes that enable this type of behavior? It seems pretty specific, and I have used this pattern a couple times before so I had a clean interface for filtering or modifying data. I just don't know how to explain the concept to anybody without going into full blown detail which might be unnecessary if there is a name for this design pattern.
To reiterate, the pattern in question is basically just using reflection within a main class method to seek out methods that exist in the child class in order to dynamically call those methods on the given data, based on a specific context.
Aucun commentaire:
Enregistrer un commentaire