472,954 Members | 1,710 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,954 software developers and data experts.

Class instantiation question

Ok, say I have a class MyClass and an __init__(self,
a, b) Say that a and b are required to be integers
for example. So my init looks like:

__init__(self, a, b):
try:
self.one = int(a)
self.two = int(b)
except ValueError:
#nice error message here
return None

I have even tried a similar example with if-else
instead of try-except, but no matter what if I call

thisInstance = MyClass(3, "somestring")

it will set self.one to 3 and self.two will be
uninitialised. The behavior I am hoping for, is that
thisInstance is not created instead(or is None). How
do I get the behavior I am looking for?

Thanks in advance,
Todd

__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

Jul 18 '05 #1
5 1444
Todd Johnson wrote:
Ok, say I have a class MyClass and an __init__(self,
a, b) Say that a and b are required to be integers
for example. So my init looks like:

__init__(self, a, b):
try:
self.one = int(a)
self.two = int(b)
except ValueError:
#nice error message here
return None

I have even tried a similar example with if-else
instead of try-except, but no matter what if I call

thisInstance = MyClass(3, "somestring")

it will set self.one to 3 and self.two will be
uninitialised. The behavior I am hoping for, is that
thisInstance is not created instead(or is None). How
do I get the behavior I am looking for?

Thanks in advance,
Todd


If I'm correct, __init__ method is somewhat different from what you
expect: it *doesn't* return values (None is just a fake return value).
Actually MyClass(...) proceeds more or less in the following way:

1) create an object
2) call __init__ with parameters passed
3) return the object's reference.

Therefore, you cannot prevent object creation in __init__. You can only
throw an exception.

Actually, I see no reason to use if/then instead try/except or maybe
even simple self.one = int(a) (that will throw if anythins goes wrong),
but if you want, for example, to create another object depending on
parameters passed, take a look at __new__ method.

regards,
anton.

Jul 18 '05 #2
Todd Johnson wrote:
Ok, say I have a class MyClass and an __init__(self,
a, b) Say that a and b are required to be integers
for example. So my init looks like:

__init__(self, a, b):
try:
self.one = int(a)
self.two = int(b)
except ValueError:
#nice error message here
return None

I have even tried a similar example with if-else
instead of try-except, but no matter what if I call

thisInstance = MyClass(3, "somestring")

it will set self.one to 3 and self.two will be
uninitialised. The behavior I am hoping for, is that
thisInstance is not created instead(or is None). How
do I get the behavior I am looking for?

1. I highly recommend you rethink your programming. Are you planning
to handle the error in the function that called the MyClass
contructor? In other words, are you doing something like this:

def some_function(a,b):
thisInstance = MyClass(a,b)
if thisInstance is None:
handle_error()
else:
do_something_useful(thisInstance)

If so, you are not taking full advantage of the exception handling
mechanism. The best way to do it is like this:

def some_function(a,b):
try:
thisInstance = MyClass(a,b)
except ValueError:
handler_error()
else:
do_something_useful(thisInstance)

As always, a larger code snippet can help us help you with that, if
you wish.
2. If you're sure the behavior you want is to return None if a or b is
not an integer, then I recommned you use a factory function:

def my_class_maker(a,b):
try:
return MyClass(a,b)
except ValueError:
return None
--
CARL BANKS http://www.aerojockey.com/software

As the newest Lady Turnpot descended into the kitchen wrapped only in
her celery-green dressing gown, her creamy bosom rising and falling
like a temperamental souffle, her tart mouth pursed in distaste, the
sous-chef whispered to the scullery boy, "I don't know what to make of
her."
--Laurel Fortuner, Montendre, France
1992 Bulwer-Lytton Fiction Contest Winner
Jul 18 '05 #3
Todd Johnson wrote:
Ok, say I have a class MyClass and an __init__(self,
a, b) Say that a and b are required to be integers
for example. So my init looks like:

__init__(self, a, b):
try:
self.one = int(a)
self.two = int(b)
except ValueError:
#nice error message here
return None

I have even tried a similar example with if-else
instead of try-except, but no matter what if I call

thisInstance = MyClass(3, "somestring")

it will set self.one to 3 and self.two will be
uninitialised. The behavior I am hoping for, is that
thisInstance is not created instead(or is None). How
do I get the behavior I am looking for?


As far as I know, the only way to prevent __init__ from creating an
instance is for __init__ to raise an exception which is NOT caught and
handled within __init__. In your example, I think simply doing

class MyClass(self, a, b):
def __init__(self, a, b):
self.one = int(a)
self.two = int(b)

without the try...except block should do it. Then the calling code can
handle the ValueError appropriately.

David

Jul 18 '05 #4
Todd Johnson <ov**********@yahoo.com> wrote:
Ok, say I have a class MyClass and an __init__(self,
a, b) Say that a and b are required to be integers
for example. So my init looks like:

__init__(self, a, b):
try:
self.one = int(a)
self.two = int(b)
except ValueError:
#nice error message here
return None

I have even tried a similar example with if-else
instead of try-except, but no matter what if I call

thisInstance = MyClass(3, "somestring")

it will set self.one to 3 and self.two will be
uninitialised. The behavior I am hoping for, is that
thisInstance is not created instead(or is None). How
do I get the behavior I am looking for?


Here's one option:
class C: .... def __init__(self, a):
.... self.a = int(a)
.... c = C("hello") Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in __init__
ValueError: invalid literal for int(): hello

This also allows the following:
try: c = C("hello") .... except ValueError: c = None
.... print c None

If you really want initialization to return None instead of raising an
exception, you can override the __new__ method of a new-style class:
class C(object): .... def __new__(cls, a):
.... try: a = int(a)
.... except ValueError: return None
.... return object.__new__(cls, a)
.... def __init__(self, a):
.... self.a = a
.... c = C(1)
c.a 1 c = C("hello")
print c

None
Jul 18 '05 #5
Todd Johnson wrote:
Ok, say I have a class MyClass and an __init__(self,
a, b) Say that a and b are required to be integers
for example. So my init looks like:

__init__(self, a, b):
try:
self.one = int(a)
self.two = int(b)
except ValueError:
#nice error message here
return None
Any return statement in __init__ MUST return None (you
get an error otherwise). The job of __init__ is
preparing the self, which is already created.
I have even tried a similar example with if-else
instead of try-except, but no matter what if I call

thisInstance = MyClass(3, "somestring")

it will set self.one to 3 and self.two will be
uninitialised. The behavior I am hoping for, is that
thisInstance is not created instead(or is None). How
do I get the behavior I am looking for?


It's not a nice architecture AT ALL, but if you
insist you can have it -- as long at least as
class MyClass is new-style, e.g., subclasses
object -- by defining a __new__ method. The
process of calling a class can be summarized as:

[[ function equivalent to calling theclass with
positional args *a and named args **k ...: ]]

result = theclass.__new__(theclass, *a, **k)
if isinstance(result, theclass):
theclass.__init__(result, *a, **k)
return result

Normally, it's best to do all the work in __init__
and thus to inherit __new__ from type object.
But that's only for the NORMAL case, where one
assumes that calling theclass always either
raises / propagates an exception OR else returns
an instance of theclass. Since you deliberately
want to break this normal, expected rule --
having the call to theclass return None instead! --
you would need to define __new__.

For example:
class theclass(object):

def __new__(cls, a, b):
self = object.__new__(cls)
try:
self.one = int(a)
self.two = int(b)
except ValueError:
#nice error message here
return None
else:
return self

I would still recommend you to reconsider the
architecture you want. Why MUST you break all
normal Pythonic expectations of users of your
class...? If you must, Python lets you -- but
MUST you, really...?
Alex

Jul 18 '05 #6

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

Similar topics

6
by: Ruud de Jong | last post by:
I have the situation where I need to construct the name of a static method, and then retrieve the corresponding function from a class object. I thought I could just use __getattribute__ for this...
7
by: Drew McCormack | last post by:
I have a C++ template class which contains a static variable whose construction registers the class with a map. Something like this: template <typename T> class M { static Registrar<M>...
3
by: Patrick Guio | last post by:
Hi, I have trouble to compile the following piece of code with g++3.4 but not with earlier version // Foo.h template<typename T> class Foo { public:
10
by: msnews.microsoft.com | last post by:
Public Class Controller Dim mx As New HelperClass 'here, where I have it now ???? Sub New() 'or here??? Dim mx As New HelperClass
23
by: mark.moore | last post by:
I know this has been asked before, but I just can't find the answer in the sea of hits... How do you forward declare a class that is *not* paramaterized, but is based on a template class? ...
5
by: Slant | last post by:
Here's a question that most will have different answers to. I'm just dying to find a solution that seems halfway automated!! There really are two seperate issues which might be answered by the...
8
by: Ole Nielsby | last post by:
I want to create (with new) and delete a forward declared class. (I'll call them Zorgs here - the real-life Zorks are platform-dependent objects (mutexes, timestamps etc.) used by a...
4
by: Devon Null | last post by:
I have been exploring the concept of abstract classes and I was curious - If I do not define a base class as abstract, will it be instantiated (hope that is the right word) when a derived class is...
29
by: Brad Pears | last post by:
Here is a simple OO design question... I have a Contract class. The user can either save an existing contract or they start off fresh with a blank contract, fill in the data and then save a...
4
by: yuanhp_china | last post by:
I define a class in A.h: template <class Tclass A{ public: void get_elem( const T&) ; };
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
1
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.