[Tutor] adding methods to native types
Sean 'Shaleh' Perry
shalehperry@attbi.com
Wed Feb 5 23:26:03 2003
On Wednesday 05 February 2003 19:59, Erik Price wrote:
> 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.
>
As of the latest python releases you can subclass list, dict, etc.
>>> class MyList(list):
=2E.. def len(self):
=2E.. return self.__len__()
=2E..=20
>>> a =3D MyList()
>>> a.append(1)
>>> a.append(2)
>>> a.append(3)
>>> a.len()
3
However it is quite Pythonic to mix functional and OO styles. Forcing a =
pure=20
OO style will move you away from common idioms and make your code feel=20
slightly less natural to the common Python coder.
Rather than fight it, you should learn to enjoy the functional choices=20
available to you. Many of us find the mix fun and less effortless.