473,387 Members | 1,678 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

__init__ style questions

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).

Heres the __init__ function I have at the moment.

class Vector3D(object):

__slots__ = ('x', 'y', 'z')

def __init__(self, x_or_iter=None, y=None, z=None):

if x_or_iter is None:
self.x = self.y = self.z = 0
elif z is None:
it = iter(x_or_iter)
self.x = float(it.next())
self.y = float(it.next())
self.z = float(it.next())
else:
self.x = float(x_or_iter)
self.y = float(y)
self.z = float(z)

A Vector3D can be constructed in 3 ways. If no parameters are given it
assumes a default of (0, 0, 0). If one parameter is given it is assumed
to be an iterable capable of giving 3 values. If 3 values are given
they are assumed to be the initial x, y, z.

And now for the ponderings...

1) Is 'overloading' like this pythonic, or should I supply alternative
contstructors?

2) I convert the input values to floats, which seems convenient because
a Vector could be constructed with integers and other objects capable
of being converted to floats. Could this hide errors?

3) I like the constructing from an iterable, but it does mean that I
can do something crazy like Vector3D("123"). Could this also hide
errors?

4) This does seem like a good candidate for __slots__, since there will
could be large-ish lists of Vector3Ds. But is it a premature
optimization?

If it was just for myself or other experienced programmers I wouldn't
be bothered about having the ability to do stupid things, because I
simply wouldnt do them! But I dont want to teach beginner programmers
bad habbits!

Any comments appreciated...

Will McGugan
--
http://www.willmcgugan.com

Oct 2 '06 #1
8 990
"Will McGugan" <wi**@willmcgugan.comwrote:
A Vector3D can be constructed in 3 ways. If no parameters are given it
assumes a default of (0, 0, 0). If one parameter is given it is assumed
to be an iterable capable of giving 3 values. If 3 values are given
they are assumed to be the initial x, y, z.

And now for the ponderings...

1) Is 'overloading' like this pythonic, or should I supply alternative
contstructors?
No it isn't Pythonic. Why not just require 3 values and move the
responsibility onto the caller to pass them correctly? They can still use
an iterator if they want:

Vector3D(a, b, c)
Vector3D(*some_iter)

Then your initialiser becomes:

def __init__(self, x=0, y=0, z=0):
self.x, self.y, self.z = x, y, z

much cleaner and also catches accidental use of iterators.

Alternatively, insist on always getting exactly 0 or 1 arguments:

Vector3D((a,b,c))
Vector3D(some_iter)

def __init__(self, (x, y, z)=(0,0,0)):
self.x, self.y, self.z = x, y, z

which is great if you already have lots of 3-tuples, but a pain otherwise
to remember to double the parentheses.
Oct 2 '06 #2
Duncan Booth wrote:
No it isn't Pythonic.
rubbish. using a single constructor that handles two common use cases is
perfectly Pythonic (especially if you're targeting casual programmers).

</F>

Oct 2 '06 #3

Duncan Booth wrote:
No it isn't Pythonic. Why not just require 3 values and move the
responsibility onto the caller to pass them correctly? They can still use
an iterator if they want:

Vector3D(a, b, c)
Vector3D(*some_iter)
I kind of liked the ability to partially use iterators. It would be
convenient for reading in from a file for example

f = file( "model.txt" )
v1 = Vector3D( f )
v2 = Vector3D( f )
v3 = Vector3D( f )

Which you couldnt do with a tuple, because the * syntac would attempt
to read the entire file (I think).
>
Then your initialiser becomes:

def __init__(self, x=0, y=0, z=0):
self.x, self.y, self.z = x, y, z

much cleaner and also catches accidental use of iterators.

Alternatively, insist on always getting exactly 0 or 1 arguments:

Vector3D((a,b,c))
Vector3D(some_iter)

def __init__(self, (x, y, z)=(0,0,0)):
self.x, self.y, self.z = x, y, z

which is great if you already have lots of 3-tuples, but a pain otherwise
to remember to double the parentheses.
Hmm. Not keen on that for the reason you mentioned. For my particular
use case there would be a lot of Vector3D 'literals'.

Oct 2 '06 #4
"Fredrik Lundh" <fr*****@pythonware.comwrote:
Duncan Booth wrote:
>No it isn't Pythonic.

rubbish. using a single constructor that handles two common use cases is
perfectly Pythonic (especially if you're targeting casual programmers).
Yes, but I don't think that the specific case the OP asked about would be
pythonic: there was no need two separate calling conventions there.
Oct 2 '06 #5
"Will McGugan" <wi**@willmcgugan.comwrote:
Duncan Booth wrote:
>No it isn't Pythonic. Why not just require 3 values and move the
responsibility onto the caller to pass them correctly? They can still
use an iterator if they want:

Vector3D(a, b, c)
Vector3D(*some_iter)

I kind of liked the ability to partially use iterators. It would be
convenient for reading in from a file for example

f = file( "model.txt" )
v1 = Vector3D( f )
v2 = Vector3D( f )
v3 = Vector3D( f )

Which you couldnt do with a tuple, because the * syntac would attempt
to read the entire file (I think).
Yes, it would, although since the implication is that your class expected
numbers and the file iterator returns strings I'm not sure how much it
matters: you are still going to have to write more code than in your
example above. e.g.

v1 = Vector3D(float(n) for n in itertools.islice(f, 3))

or with my variant:

v1 = Vector3D(*(float(n) for n in itertools.islice(f, 3)))
I think my main objection to your code was that it introduced too many ways
for the constructor to do unexpected things silently. e.g. your suggestion
Vector3D("abc"), or Vector3D((1,2,3,4)) and I don't like errors going
uncaught. That's why I think it is better to pass in exactly the arguments
you need and convert them at the point where you can tell what the ambigous
construction actually meant. I have no objection though to e.g. a class
factory method which does all of this:

@classmethod
def fromStringSequence(cls, iter):
return cls(*(float(n) for n in itertools.islice(iter, 3)))

because that still makes you decide at the point of call whether you want:

v1 = Vector3D(1, 2, 3)

or
v1 = Vector3D.fromStringSequence(f)
Oct 2 '06 #6

Duncan Booth wrote:
>
Yes, it would, although since the implication is that your class expected
numbers and the file iterator returns strings I'm not sure how much it
matters: you are still going to have to write more code than in your
example above. e.g.

v1 = Vector3D(float(n) for n in itertools.islice(f, 3))

or with my variant:

v1 = Vector3D(*(float(n) for n in itertools.islice(f, 3)))
The generator expression wouldnt really be neccesary since the
constructor converts the iterated values to floats.

But! I understand your objection. It doesn't quite fit with 'explicit
is better than implicit'. Im just debating the trade-off with catching
foolish mistakes and making it easier to use for beginners.

Thanks.

Oct 2 '06 #7
Will McGugan wrote:
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).

Heres the __init__ function I have at the moment.

class Vector3D(object):

__slots__ = ('x', 'y', 'z')

def __init__(self, x_or_iter=None, y=None, z=None):

if x_or_iter is None:
self.x = self.y = self.z = 0
elif z is None:
it = iter(x_or_iter)
self.x = float(it.next())
self.y = float(it.next())
self.z = float(it.next())
else:
self.x = float(x_or_iter)
self.y = float(y)
self.z = float(z)

A Vector3D can be constructed in 3 ways. If no parameters are given it
assumes a default of (0, 0, 0). If one parameter is given it is assumed
to be an iterable capable of giving 3 values. If 3 values are given
they are assumed to be the initial x, y, z.
here's a slightly different approach:
class Vector3D(object):
__slots__ = ('x', 'y', 'z')

def __init__(self, X1=None, X2=None, X3=None):
if X3 is not None:
#assume 3 numbers
self.x = X1
self.y = X2
self.z = X3
else:
X1 = X1 or (0,0,0)
X2 = X2 or (0,0,0)
self.x = X1[0] - X2[0]
self.y = X1[1] - X2[1]
self.z = X1[2] - X2[2]

def __getitem__(self, index):
return getattr(self,self.__slots__[index])

def __str__(self):
return '(%s, %s, %s)' % (self.x, self.y, self.z )

u = Vector3D()
print u
u = Vector3D(3,4,5)
print u
u, v = Vector3D( [1,2,3] ), Vector3D( (3,2,1) )
print u, v
w = Vector3D( u,v )
print w
w = Vector3D( u, (2,2,2))
print w

(0, 0, 0)
(3, 4, 5)
(1, 2, 3) (3, 2, 1)
(-2, 0, 2)
(-1, 0, 1)

Gerard

Oct 2 '06 #8
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

Oct 2 '06 #9

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

Similar topics

4
by: Martin Maney | last post by:
I've been to the cookbook (both forms, since they're sometimes usefully different), but that gave rise to more questions than answers. Heck, let me pull some of them up while I'm at it. ...
3
by: Iyer, Prasad C | last post by:
I am new to python. I have few questions a. Is there something like function overloading in python? b. Can I overload __init__ method Thanks in advance regards
7
by: Kent Johnson | last post by:
Are there any best practice guidelines for when to use super(Class, self).__init__() vs Base.__init__(self) to call a base class __init__()? The super() method only works correctly in multiple...
2
by: crystalattice | last post by:
I'm making a GUI for a console-based program I just wrote. I figured it would be mostly straight forward to convert it over in wxPython but now I'm confused. In my console program, I have...
4
by: Noah | last post by:
Am I the only one that finds the super function to be confusing? I have a base class that inherits from object. In other words new style class: class foo (object): def __init__ (self, arg_A,...
8
by: kelin,zzf818 | last post by:
Hi, Today I read the following sentences, but I can not understand what does the __init__ method of a class do? __init__ is called immediately after an instance of the class is created. It...
2
by: Alan Isaac | last post by:
I am probably confused about immutable types. But for now my questions boil down to these two: - what does ``tuple.__init__`` do? - what is the signature of ``tuple.__init__``? These...
4
by: Steven D'Aprano | last post by:
When you call a new-style class, the __new__ method is called with the user-supplied arguments, followed by the __init__ method with the same arguments. I would like to modify the arguments...
3
by: Torsten Mohr | last post by:
Hi, i have some questions related to new style classes, they look quite useful but i wonder if somebody can give me an example on constructors using __new__ and on using __init__ ? I just see...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

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.