Lets say I have a class representing a chemical compound
class Compound(networkx.Graph):
def __init__(self):
super(Compound, self).__init__()
And lets say that I want to add some extra functionality onto a chemical compound. It should probably inherit from Compound. But is it okay to just use it as a wrapper for Compound? For example
class Acid(Compound):
def __init__(self, compound, *other_data):
self.__dict__.update(compound.__dict__)
Basically, this class would just have pointers to the underlying class and then let me add functionality without having to copy things. Does this make sense? Is it reasonable? Am I even doing it right?
1
You should probably use inheritance in this case, but wrapping the object you with to extend is fine as well. In fact, the technique is useful enough to have a name: the Decorator Pattern.
The usual way to forward all calls in Python is not to mess around with __dict__
, but to override __getattr__
(“explicit is better than implicit”):
class A(object):
def __init__(self, *args, **kwargs):
self._b = B(*args, **kwargs)
def __getattr__(self, name):
return getattr(self._b, name)
__getattr__
only fires when the name is not found the usual way, so you are free to add or override names in A
which you do not want to be forwarded to B
.
2