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):

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?

  • You are both inheriting and wrapping. If Acid is a kind of Compound, then inherit, not wrap. You don't need to copy things if you inherit; that is kind of the point of inheritance. Dec 1, 2014 at 9:33

1 Answer 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.

  • How would you suggest using inheritance differently? As is, Acid inherits from Compound. Dec 1, 2014 at 8:53
  • If Acid inherits Compound then why do you need to wrap a Compound as well? Your code seems to be saying that Acid both is a Compound and has a Compound. That seems incorrect to me. Dec 1, 2014 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.