Christian Dieterich wrote:

Hi,

I need to create many instances of a class D that inherits from a class B. Since the constructor of B is expensive I'd like to execute it only if it's really unavoidable. Below is an example and two workarounds, but I feel they are not really good solutions. Does somebody have any ideas how to inherit the data attributes and the methods of a class without calling it's constructor over and over again?

You could try making D a container for B instead of a subclass:

class D(object):
    def __init__(self, ...):
        self._B = None
    def __getattr__(self, attr):
        if self._B is None:
            self._B = B()
        return getattr(self._B, attr)

Include something similar for __setattr__(), and you should be in business.

If it will work for numerous D instances to share a single B instance (as one of your workarounds suggests), then you can give D's __init__() a B parameter that defaults to None.

Jeff Shannon
Technician/Programmer
Credit International

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to