How to instantiate a different class in a constructor?

Paul McGuire ptmcg at austin.rr.com
Tue Jan 23 09:45:26 EST 2007


On Jan 23, 5:09 am, GiBo <g... at gentlemail.com> wrote:
> Hi all,
>
> I have a class URI and a bunch of derived sub-classes for example
> HttpURI, FtpURI, HttpsURI, etc. (this is an example, I know there is
> module urllib & friends, however my actual problem however maps very
> well to this example).
>
> Now I want to pass a string to constructor of URI() and get an instance
> of one of the subclasses back. For example uri=URI('http://abcd/...')
> will make 'uri' an instance of HttpURI class, not instance of URI.
>
> To achieve this I have a list of all subclasses of URI and try to
> instantiate one by one in URI.__new__(). In the case I pass e.g. FTP URI
> to HttpURI constructor it raises ValueError exception and I want to test
> HttpsURI, FtpURI, etc.
>
> For now I have this code:
>
> =====
> class URI(object):
>         def __new__(self, arg):
>                 for subclass in subclasses:
>                         try:
>                                 instance = object.__new__(subclass, arg)
>                                 return instance
>                         except ValueError, e:
>                                 print "Ignoring: %s" % e
>                 raise ValueError("URI format not recognized" % arg)
>

<snip>

Call __new__ and subclass.__init__ explicitly:

class URI(object):
        def __new__(self, arg):
                for subclass in subclasses:
                        try:
                                instance = object.__new__(subclass)
                                instance.__init__(arg)
                                return instance
                        except ValueError, e:
                                print "Ignoring: %s" % e
                raise ValueError("URI format not recognized" % arg)

(Might I suggest 4-space indents vs. 8?)

-- Paul




More information about the Python-list mailing list