473,830 Members | 2,019 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to instantiate a different class in a constructor?

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)

class HttpURI(URI):
def __init__(self, arg):
if not arg.startswith( "http://"):
raise ValueError("%s: not a HTTP URI" % arg)
self._uri = arg

class FtpURI(URI):
def __init__(self, arg):
if not arg.startswith( "ftp://"):
raise ValueError("%s: not a FTP URI")
self._uri = arg

subclasses = [HttpURI, FtpURI]

if __name__ == "__main__":
print "Testing HTTP URI"
uri = URI("http://server/path")
print uri

print "Testing FTP URI"
uri = URI("ftp://server/path")
print uri
=====

The problem is that ValueError exception raised in HttpURI.__init_ _() is
not handled in URI.__new__():

-----
~$ ./tst.py
Testing HTTP URI
<__main__.HttpU RI object at 0x808572c> # this is good
Testing FTP URI
Traceback (most recent call last):
File "./tst.py", line 35, in <module>
uri = URI("ftp://server/path")
File "./tst.py", line 18, in __init__
raise ValueError("%s: not a HTTP URI" % arg)
ValueError: ftp://server/path: not a HTTP URI # this is bad
-----

When I change the __init__ methods of subclasses to __new__ I instead get:

-----
../tst.py
Testing HTTP URI
Traceback (most recent call last):
File "./tst.py", line 29, in <module>
uri = URI("http://server/path")
File "./tst.py", line 7, in __new__
instance = object.__new__( subclass, arg)
TypeError: default __new__ takes no parameters
-----

Does anyone have any hints on how to solve this problem? (other than
using urllib or other standard modules - as I said this is just to
demonstrate the nature of my problem).

Thanks!
GiBo
Jan 23 '07 #1
4 1686
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.
<snip/>
Use a factory function:

class UriBase(object) :
REGISTRY = {}

class HttpUri(UriBase ):
pass

UriBase.REGISTR Y['http'] = HttpUri

def URI(arg):
return UriBase.REGISTR Y[get_protocol(ar g)](arg)

This is untested and could be enhanced by e.g. using metaclasses to perform
the registration automagicall, but I think you get the idea.

Diez
Jan 23 '07 #2
On Jan 23, 5:09 am, GiBo <g...@gentlemai l.comwrote:
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

Jan 23 '07 #3
Paul McGuire wrote:
On Jan 23, 5:09 am, GiBo <g...@gentlemai l.comwrote:
>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
Jan 23 '07 #4
At Tuesday 23/1/2007 20:07, GiBo wrote:
>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__ ().
At instance creation, when type(name, bases, ns) is invoked, after
the __new__ call, but only if the returned object is an instance of
type. This happens in function type_call (in typeobject.c)
--
Gabriel Genellina
Softlab SRL


_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Jan 24 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2483
by: jerrygarciuh | last post by:
Hello, Is it possible to instantiate a child class within the constructor of its parent? eg Class DBI extends DB { function DBI() { // explicit parent constructor call
5
2378
by: Glenn Serpas | last post by:
I have Class A and Class B .. Class B has a private member that is a pointer to a Class A object. private: B *mypointer ; I instantiate the A object A* myobject new = A();
3
17462
by: ernesto | last post by:
Hi everybody: I have the following implementations: class A { public: virtual int GetValue() = 0; };
16
2188
by: gabon | last post by:
Due a big project I would like to create different javascript classes and assign them to divs. But how? :) I know the usage of prototype but given that this could be possible: function newDiv(){...} newDiv.prototype=new div(); and of course it isn't. How to instantiate that class? var newDiv_instance=document.createElement("div");
8
11256
by: julian_m | last post by:
I'm having problems with include. I wrote a small example which shows what's going on... I should say that the problems started after I moved to a shared server. All was working fine in my local server... file test.php --------------------------------------------------- <?php
4
1495
by: Andrew Backer | last post by:
Hello, I am having a problem creating a class dynamically. The class I have is a base class of another, and the parent class has the constructor (which takes one argument). The base class (Class1, below) does not have any constructors. I am using code like this to create it, and it's blowing up : Dim res As Object = Activator.CreateInstance( _ GetType( MyNameSpace.Class1 ), _
1
2840
by: learning | last post by:
Hi how can I instaltiate a class and call its method. the class has non default constructor. all examples i see only with class of defatul constructor. I am trying to pull the unit test out from the product source code, but still want to execute them under nunit. I am trying this idea on nunit sample source code. Here is my class and the experiemental code: both money.cs and Imoney.cs is compiled to cs_money.dll. then I create another...
0
1248
by: Fei Liu | last post by:
Hello, We all know that a template function can automatically deduce its parameter type and instantiate, e.g. template <tpyename T> void func(T a); func(0.f); This will cause func<floatto be instantiated. The user does not have
3
3587
by: Fei Liu | last post by:
Hello, We all know that a template function can automatically deduce its parameter type and instantiate, e.g. template <tpyename T> void func(T a); func(0.f); This will cause func<floatto be instantiated. The user does not have
0
9793
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10491
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10526
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10206
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7746
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6951
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5780
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4411
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3959
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.