[Tutor] adding methods to native types
Don Arnold
Don Arnold" <darnold02@sprynet.com
Wed Feb 5 23:08:02 2003
----- Original Message -----
From: "Erik Price" <erikprice@mac.com>
To: <tutor@python.org>
Sent: Wednesday, February 05, 2003 9:59 PM
Subject: [Tutor] adding methods to native types
> Pardon me for asking such a strange question (perhaps), but is there
> any way to add methods to the native types in Python? I wrote my first
> Python script in a long time today and I pined for the length() method
> of Java's List type -- it took me a while to figure out that there's no
> way to determine the length of a list using a list method, you have to
> use the len() function.
>
> It led me to wonder if it's possible to subclass the native types in
> Python and add additional features. If not, there's nothing to stop
> one from composing the list within another class and adding the
> additional features, which actually relieves me of the burden of
> ensuring that the subclass is completely compatible with the
> internal/external implementation of the base class, but I'm curious if
> you can do it.
>
> Essentially, I prefer
>
> "string".split("")
>
> to
>
> split("", string)
>
> and wanted to do
>
> list.len()
>
> instead of
>
> len(list)
>
Lists already have a builtin magical method for this (which is what the len
function calls to get its value):
Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> a = [1,2,3,4,5]
>>> a.__len__()
5
>>>
> Thanks,
>
> Erik
>
> --
> Erik Price
>
> email: erikprice@mac.com
> jabber: erikprice@jabber.org
HTH,
Don