__init__ style questions
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Mon Oct 2 09:20:31 EDT 2006
Will McGugan:
> I am writting a Vector3D class as a teaching aid (not for me, for
> others), and I find myself pondering over the __init__ function. I want
> it to be as easy to use as possible (speed is a secondary
> consideration).
If optimizations are less important, then don't use __slots__, it
simplifies OOP management of it.
I think that accepting a single iterable too makes the calling a bit
too much elastic, so it can produce silent problems. Something like
this may be better:
from itertools import imap
class Vector3D(object):
def __init__(self, *args):
len_args = len(args)
if len_args == 3:
self.x, self.y, self.z = imap(float, args)
elif len_args == 0:
self.x = self.y = self.z = 0
else:
raise TypeError("...")
If you don't like imap, you can change that code.
If you want to accept single parameter too then you can use something
like:
class Vector3D(object):
def __init__(self, *args):
len_args = len(args)
if len_args == 3:
self.x, self.y, self.z = imap(float, args)
elif len_args == 1:
self.x, self.y, self.z = imap(float, args[0])
elif len_args == 0:
self.x = self.y = self.z = 0
else:
raise TypeError("...")
If you don't like the explicit raising of an error you may use:
class Vector3D(object):
def __init__(self, first=None, *other):
if first:
if other:
self.x = float(first)
self.y, self.z = imap(float, other)
else:
self.x, self.y, self.z = imap(float, first)
else:
self.x = self.y = self.z = 0
But this last code is less readable.
Bye,
bearophile
More information about the Python-list
mailing list