Posts

Showing posts with the label object-oriented programming

Do Pythonistas Understand Data Abstraction?

I was just reading this page on why not to use getter and setter functions in Python, and realized the author doesn't seem to have any idea what data abstraction is: "In Java, you have to use getters and setters because using public fields gives you no opportunity to go back and change your mind later to using getters and setters." This was never the reason I used a getter or setter method in Java! You use getters and setters to achieve data abstraction : "The representation details are confined to only a small set of procedures that create and manipulate data, and all other access is indirectly via only these procedures." I had a class GridAgent where the agent held its position on a grid, among other things. But then I wanted to re-do this, so that the position was held in a cell, which held the agent. I had (sometimes) done things the "Pythonic" way, but just accessing the position variable, and of course I had to find every instance of th...

The Problem of the Fragile Base Class

If (almost) all classes inherit from a single base class in a system, we get the problem of the fragile base class : a change to that single base class can break subclasses in non-obvious ways. But this problem must be weighed against the advantages of a single base class. The foremost advantage is probably that one can add a capability to the base class and have it available to every class in the system if they all inherit from that base class. What's more, the very problem can be an advantage: if some capability is provided in the base class, and there is a problem with it, the fix will also be all in one place! The upshot: if you use a single base class, be very careful about changing it!

How to make your Python classes document their own inheritance tree

Image
First we connect our base Node class to a graph, which prevents searching further up the inheritance tree and trying to add 'Object' itself, which don't care to do:                 def __init__(self, name):         self.ntype = self.__class__.__name__         if not Node.node_added:             Node.class_graph.add_node(                 Node.__name__)         # now search the class graph         # to see if the current class         # is there:         if self.ntype not in Node.class_graph:             self.__class__.connect_to_class_tree() And he...

Painless re-factoring of a class hierarchy

I had the following inheritance tree: Environment______SpatialEnv______GridEnv This was wrong. SpatialEnv implemented a complex plane, which GridEnv just did not need: it is a grid, after all! What I really wanted was:                                                         ___GridEnv                                                         | Environment______SpatialEnv___|                                                         |                                   ...