subclassing Python types

Steve Holden steve at holdenweb.com
Thu Aug 30 15:43:25 EDT 2007


zzbbaadd at aol.com wrote:
> On Aug 30, 12:13 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
>> On Aug 30, 8:00 pm, zzbba... at aol.com wrote:
>>
>>> I have read that you can derive from the base classes such as str,
>>> list, dict.
>>> I guess this would look like:
>>> def MyString(str):
>>> def MyList(list):
>>> def MyDict(dict):
>> You mean
>>
>> class MyString(str):
>> ...
>>
>>> How do you access the data that is contained in the super class?
>> The same way that you access plain strings, lists or dicts: use the
>> methods of the super class.
>>
> 
> I don't know what name I would use to call a method:
> 
> 
> class MyString(str):
>     def __init__(strInput):
>        ????? = strInput
> 
> 
I think your understanding of Python needs to advance a little before 
you start trying to do something like this. It's the __new__() method 
you need to be overriding, not the __init__() method.

 >>> class MyString(str):
...   def __new__(cls, val):
...     return str.__new__(cls, val)
...
 >>> s = MyString("1234")
 >>> s
'1234'
 >>> type(s)
<class '__main__.MyString'>
 >>>

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list