Is it possible to have instance variables in subclasses of builtins?

Russell Blau russblau at hotmail.com
Wed Jun 16 09:02:18 EDT 2004


"Kenneth McDonald" <kenneth.m.mcdonald at sbcglobal.net> wrote in message
news:slrnccutjp.3qk.kenneth.m.mcdonald at g4.gateway.2wire.net...
> I've recently used subclasses of the builtin str class to good effect.
> However, I've been unable to do the following:
>
> 1) Call the constructor with a number of arguments other than
> the number of arguments taken by the 'str' constructor.
>
> 2) Create and use instance variables (eg. 'self.x=1') in
> the same way that I can in a 'normal' class.
>
> As an example of what I mean, here's a short little session:
>
> >>> class a(str):
> ...     def __init__(self, a, b):
> ...             str.__init__(a)
> ...             self.b = b
> ...
> >>> x = a("h", "g")
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   TypeError: str() takes at most 1 argument (2 given)
> >>>

The problem is that "str" is an immutable type.  Therefore, to change the
constructor, you need to override the __new__ method.  See
http://www.python.org/2.2.1/descrintro.html#__new__

Here's an example:

>>> class two(str):
   def __new__(cls, a, b):
       return str.__new__(cls, a)
   def __init__(self, a, b):
       self.b = b

>>> z = two("g", "h")
>>> z
'g'
>>> z.b
'h'

Note that both arguments (a and b) get passed to both the __new__ and
__init__ methods, and each one just ignores the one it doesn't need.


-- 
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.





More information about the Python-list mailing list