How to instantiate a different class in a constructor?

GiBo gibo at gentlemail.com
Tue Jan 23 18:07:08 EST 2007


Paul McGuire wrote:
> 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:

Thanks! That's it :-)

BTW When is the subclass.__init__() method invoked if I don't explicitly
call it from __new__()? Apparently not from baseclass.__new__() nor from
object.__new__().

GiBo



More information about the Python-list mailing list