Calling parent constructor with different argument list

P

pinkisntwell

class Vertex(tuple):
pass

class Positioned_Vertex(Vertex):

def __init__(self, a, b):
Vertex.__init__(a)

a=Positioned_Vertex((0,0,0), 1)

This gives:

TypeError: tuple() takes at most 1 argument (2 given)

It looks like the explicit call to Vertex.__init__ is never made and
Vertex.__init__ is implicitly called when a Positioned_Vertex is
created. Is there a way to work around this and call the constructor
with the intended argument list?
 
M

Mark Lawrence

pinkisntwell said:
class Vertex(tuple):
pass

class Positioned_Vertex(Vertex):

def __init__(self, a, b):
def __init__(self, a): # just take out b
Vertex.__init__(a)

a=Positioned_Vertex((0,0,0), 1)
a=Positioned_Vertex( ( (0,0,0), 1) ) # and add a pair of brackets
print a
This gives:

TypeError: tuple() takes at most 1 argument (2 given)

It looks like the explicit call to Vertex.__init__ is never made and
Vertex.__init__ is implicitly called when a Positioned_Vertex is
created. Is there a way to work around this and call the constructor
with the intended argument list?
Simplest way to get it to work is above using Python 2.6.2 on Windows.
I'm sure there are variations depending on your use case, but I'll leave
that to the experts.
 
G

Gabriel Genellina

class Vertex(tuple):
pass

class Positioned_Vertex(Vertex):

def __init__(self, a, b):
Vertex.__init__(a)

a=Positioned_Vertex((0,0,0), 1)

This gives:

TypeError: tuple() takes at most 1 argument (2 given)

It looks like the explicit call to Vertex.__init__ is never made and
Vertex.__init__ is implicitly called when a Positioned_Vertex is
created. Is there a way to work around this and call the constructor
with the intended argument list?

The tuple constructor (like numbers, strings, and other immutable objects)
never calls __init__. You have to override __new__ instead:

py> class Point3D(tuple):
.... def __new__(cls, x, y, z):
.... obj = super(Point3D, cls).__new__(cls, (x,y,z))
.... return obj
....
py> a = Point3D(10, 20, 30)
py> a
(10, 20, 30)
py> type(a)
<class '__main__.Point3D'>

See http://docs.python.org/reference/datamodel.html#basic-customization
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top