__init__ question
Moshe Zadka
moshez at server.python.net
Tue Aug 10 09:24:26 EDT 1999
[Adrian Eyre, in response to the following challenge:
a = Vector() # x=0 y=0 z=0
a = Vector( 1) # x=1 y=1 z=1
a = Vector( 1, 2, 3) # x=1 y=2 z=3]
How about:
>>> class Vector:
... def __init__(self, *args):
... print args
...
>>> v=Vector()
()
>>> v=Vector(1)
(1,)
>>> v=Vector(1,2)
(1, 2)
The only problem with this solution is that you have to parse
args yourself (raising TypeErrors for wrong number of args, etc.),
and having no keyword arguments, as in
Vector(z=5) # x=0, y=0
A quicker, easier and more intuitive solution is:
class Vector:
def __init__(self, x=0, y=0, z=0):
self.x, self.y, self.z = x, y, z
all examples from the original post, plus my own, work with the added
benefit Python does all argument parsing for us.
More information about the Python-list
mailing list