Question about extending tuple

A

abcd

I wanted to extend tuple but ran into a problem. Here is what I
thought would work

class MyTuple(tuple):
def __init__(self, *args):
tuple.__init__(self, args)

x = MyTuple(1,2,3,4)

That gives me...

TypeError: tuple() takes at most 1 argument (4 given).

However, this call works:

x = MyTuple((1,2,3,4))

I am perplexed only because "args" is a tuple by the definition of
*args. Anyone?
 
G

Georg Brandl

abcd said:
I wanted to extend tuple but ran into a problem. Here is what I
thought would work

class MyTuple(tuple):
def __init__(self, *args):
tuple.__init__(self, args)

x = MyTuple(1,2,3,4)

That gives me...

TypeError: tuple() takes at most 1 argument (4 given).

However, this call works:

x = MyTuple((1,2,3,4))

I am perplexed only because "args" is a tuple by the definition of
*args. Anyone?

As an immutable type, tuple makes use of __new__.

class MyTuple(tuple):
def __new__(cls, *args):
return tuple.__new__(cls, args)

should work.

Georg
 
A

abcd

As an immutable type, tuple makes use of __new__.
class MyTuple(tuple):
def __new__(cls, *args):
return tuple.__new__(cls, args)

should work.

Georg

strange. not very consistent.
 
G

Georg Brandl

abcd said:
strange. not very consistent.

On the contrary -- __new__ *and* __init__ exist for all types.
The only difference is where a specific object is initialized, and
therefore which method you have to override.

__new__ is a static method (it doesn't need to be declared as one,
this is done automatically as it predates the introduction of
staticmethod()) which is called to *construct* an instance.
This can only be done once for a specific object since each call to
__new__ will result in a *new* object. In other words, this is
perfect for immutable objects -- once created, never changed.

__init__, OTOH, is called on the *instance* to initialize it. Of
course, this process can be repeated, and is therefore apt for
mutable objects like lists.

I hope you see now why it is consistent.

Georg
 

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,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top