Python-list Info Page

Robert Brewer fumanchu at amor.org
Sun Oct 31 05:42:20 CET 2004


Gary Robinson wrote:
> I am trying to understand a couple of nuances of inheriting from the 
> tuple type.
> 
> The following class definition works nicely:
> 
> class Test(tuple):
>     def __init__(self, tup):
>         self.x = 5
>         self = tup        
> a = Test((1,2))
> print a, a.x
> 
> The result of that print is "(1, 2), 5". 
> 
> But the following version:
> 
> class Test(tuple):
>     def __init__(self, tup):
>         self = tup
>         self.x = 5
> a = Test((1,2))
> 
> blows up in Python 2.3, complaining that attribute x doesn't exist.
> 
> I'm not clear on why one works and not the other, or whether 
> there's a 
> better syntax for assigning an attribute to a tuple subclass in the 
> __init__() method.
> 
> Anyone have any  thoughts??

Override __new__ as described here:

http://www.python.org/2.2.3/descrintro.html#__new__

>>> class Test(tuple):
... 	def __new__(cls, tpl):
... 		return tuple.__new__(cls, tpl)
... 	def __init__(self, tpl):
... 		self.x = 5
... 		
>>> a = Test((1, 2))
>>> a.x
5
>>> a
(1, 2)
>>> type(a)
<class '__main__.Test'>

Also, you can't rebind 'self' within __init__ and expect any reasonable
results. Remember that assignment in Python doesn't bind objects to
*variables*, it binds *names* to objects.
http://docs.python.org/ref/naming.html So when you write "self = tup",
you are simply overwriting the name "self", not the actual object
instance to which "self" referred before you overwrote it. Read
http://effbot.org/zone/python-objects.htm for a refresher.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list