can a class intantiate itself to None?
Alex Martelli
aleaxit at yahoo.com
Fri Mar 16 15:39:03 EST 2001
"Timothy Grant" <tjg at exceptionalminds.com> wrote in message
news:mailman.984770427.21248.python-list at python.org...
> I'd like to create a class that can instantiate itself to None
> when instantiation fails...
>
> class foo:
> def __init__(self, bar):
> if type(bar) == StringType:
> self.data = 'This is a String'
>
>
> x = foo('a')
>
> y = foo(1) # In this instance I would like y to be None
>
> So, can it be done, or do I need to raise an exception, catch
> it and then set y to None?
The best solution is to use a factory function, in which
you may test whatever you wish and return an instance
of your class, None, or other values yet.
class foo:
def __init__(self, bar):
self.data = 'this is a string'
_foo = foo
def foo(bar):
if type(bar)==type(''):
return _foo(bar)
return None
Note that it's quite possible to 'cover' the foo entry of
this module (representing the class) with another (naming
the function), while having the __name__ of the class
object stay 'foo' as desired.
Alex
Alex
More information about the Python-list
mailing list