Class instantiation question
anton muhin
antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Tue Oct 7 15:06:59 EDT 2003
More information about the Python-list mailing list
Tue Oct 7 15:06:59 EDT 2003
- Previous message (by thread): Class instantiation question
- Next message (by thread): Class instantiation question
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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.
- Previous message (by thread): Class instantiation question
- Next message (by thread): Class instantiation question
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list