473,323 Members | 1,537 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,323 software developers and data experts.

Like overloading __init__(), but how?

I know that Python doesn't do method overloading like
C++ and Java do, but how am I supposed to do something
like this:

--------------------- incorrect ------------------------
#!/usr/bin/python

class Point3d:
pass

class Vector3d:
"""A vector in three-dimensional cartesian space."""

def __init__( self ):
"""Create a Vector3d with some reasonable default value."""
x, y, z = 0.0, 0.0, 0.0
def __init__( self, x_from, y_from, z_from,
x_to, y_to, z_to ):
"""Create a Vector3d from x-y-z coords."""
# ...
pass
def __init__( self, point_from, point_to ):
"""Create a Vector3d from two Point3d objects."""
# ...
pass
def __init__( self, same_as_this_vec ):
"""Create a Vector3d from a copy of another one."""
# ...
pass

p = Point3d()
p2 = Point3d()
# v = Vector3d( p2, p ) -- Nope. Only the last __init__() counts.

---------------------- /incorrect -------------------------------

Thanks.

--
--- if replying via email, remove zees ---
Jul 18 '05 #1
4 6607
John M. Gabriele wrote:
class Vector3d:
def __init__(self):
...
def __init__(self, x_from, y_from, z_from, x_to, y_to, z_to):
...
def __init__(self, point_from, point_to):
...
def __init__(self, same_as_this_vec):
...


My preferred option is to break these into different methods. I pick
the xyz-coords (and the empty coords) __init__ as the most basic cases,
but if you find one of the other cases to be more basic, the
modification should be pretty simple.

class Vector3d(object):
# define init to take only xyz coords (missing coords default to 0)
# this covers your first two cases, I think
def __init__(self, x_from=0.0, y_from=0.0, z_from=0.0,
x_to=0.0, y_to=0.0, z_to=0.0):
...

# define a classmethod that creates a Vector3d from points
# this covers your third case
@classmethod
def from_points(cls, point_from, point_to):
...
return cls(x_from=..., y_from=..., ...)

# define copy as an instance method, not a constructor
# this covers your fourth case
def copy(self):
...
return type(self)(x_from=..., y_from=..., ...)
Another possibility is to play around with *args:

class Vector3d(object):
def __init__(self, *args):
if not args:
# constructor with no arguments
elif len(args) == 6:
# constructor with xyz coords
elif len(args) == 2:
# constructor with points
elif len(args) == 1:
# copy constructor
else:
raise TypeError('expected 0, 1, 2 or 6 args, got %i' %
len(args))

But this can get really ugly really quick.

HTH,

STeVe
Jul 18 '05 #2
djw
This was discussed only days ago:

http://groups-beta.google.com/group/...1c924746532316

-Don
John M. Gabriele wrote:
I know that Python doesn't do method overloading like
C++ and Java do, but how am I supposed to do something
like this:

--------------------- incorrect ------------------------
#!/usr/bin/python

class Point3d:
pass

class Vector3d:
"""A vector in three-dimensional cartesian space."""

def __init__( self ):
"""Create a Vector3d with some reasonable default value."""
x, y, z = 0.0, 0.0, 0.0
def __init__( self, x_from, y_from, z_from,
x_to, y_to, z_to ):
"""Create a Vector3d from x-y-z coords."""
# ...
pass
def __init__( self, point_from, point_to ):
"""Create a Vector3d from two Point3d objects."""
# ...
pass
def __init__( self, same_as_this_vec ):
"""Create a Vector3d from a copy of another one."""
# ...
pass

p = Point3d()
p2 = Point3d()
# v = Vector3d( p2, p ) -- Nope. Only the last __init__() counts.

---------------------- /incorrect -------------------------------

Thanks.

Jul 18 '05 #3
John M. Gabriele wrote:
I know that Python doesn't do method overloading like
C++ and Java do, but how am I supposed to do something
like this:
This was just discussed. See
http://tinyurl.com/6zo3g

Kent

--------------------- incorrect ------------------------
#!/usr/bin/python

class Point3d:
pass

class Vector3d:
"""A vector in three-dimensional cartesian space."""

def __init__( self ):
"""Create a Vector3d with some reasonable default value."""
x, y, z = 0.0, 0.0, 0.0
def __init__( self, x_from, y_from, z_from,
x_to, y_to, z_to ):
"""Create a Vector3d from x-y-z coords."""
# ...
pass
def __init__( self, point_from, point_to ):
"""Create a Vector3d from two Point3d objects."""
# ...
pass
def __init__( self, same_as_this_vec ):
"""Create a Vector3d from a copy of another one."""
# ...
pass

p = Point3d()
p2 = Point3d()
# v = Vector3d( p2, p ) -- Nope. Only the last __init__() counts.

---------------------- /incorrect -------------------------------

Thanks.

Jul 18 '05 #4
On Wed, 23 Feb 2005 21:32:52 -0700, Steven Bethard wrote:
[snip]
Another possibility is to play around with *args:

class Vector3d(object):
def __init__(self, *args):
if not args:
# constructor with no arguments
elif len(args) == 6:
# constructor with xyz coords
elif len(args) == 2:
# constructor with points
elif len(args) == 1:
# copy constructor
else:
raise TypeError('expected 0, 1, 2 or 6 args, got %i' %
len(args))

But this can get really ugly really quick.

HTH,

STeVe


Thanks STeVe. I think, for now, I'll probably stick with
the easier but less elegant way of checking *args. I guess
I could compare args[0].__class__.__name__ against 'Point3d',
'Vector3d', or just 'float'.

Didn't realize this topic came up recently. Sorry for the
duplication.

---J

--
--- if replying via email, remove zees ---
Jul 18 '05 #5

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

Similar topics

25
by: Rim | last post by:
Hi, I have been thinking about how to overload the assign operation '='. In many cases, I wanted to provide users of my packages a natural interface to the extended built-in types I created for...
1
by: Benoît Dejean | last post by:
class TargetWrapper(dict): def __init__(self, **kwargs): dict.__init__(self, kwargs) __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__
1
by: Fuzzyman | last post by:
I've been programming in python for a few months now - and returning to programming after a gap of about ten years I've really enjoyed learning python. I've just made my first forays into...
2
by: Sergey Krushinsky | last post by:
Hello all, Is there a common way to emulate constructor overloading in Python class? For instanse, I have 3 classes: 1/ Polar - to hold polar coordinates; 2/ Cartesian - to hold cartesian...
33
by: Jacek Generowicz | last post by:
I would like to write a metaclass which would allow me to overload names in the definition of its instances, like this class Foo(object): __metaclass__ = OverloadingClass att = 1 att = 3
9
by: Martin Häcker | last post by:
Hi there, I just tried to run this code and failed miserably - though I dunno why. Could any of you please enlighten me why this doesn't work? Thanks a bunch. --- snip --- import unittest...
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
11
by: placid | last post by:
Hi all, Is it possible to be able to do the following in Python? class Test: def __init__(self): pass def puts(self, str): print str
4
by: Benny the Guard | last post by:
Working on a class that I would use multiple constructors in C++ since I have different ways of creating the data. Tried this in python by defining multiple __init__ methods but to no avail, it...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.