RE: Python-list Info Page
From: Robert Brewer (fumanchu_at_amor.org)
Date: 10/31/04
- Next message: Michael Fuhr: "Re: Python and MySQL 4.1"
- Previous message: Aahz: "Re: What is Python's answer to Perl 6?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 30 Oct 2004 21:42:20 -0700 To: "Gary Robinson" <grobinson@transpose.com>, <python-list@python.org>
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@amor.org
- Next message: Michael Fuhr: "Re: Python and MySQL 4.1"
- Previous message: Aahz: "Re: What is Python's answer to Perl 6?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]