[Tutor] adding methods to native types

Sean 'Shaleh' Perry shalehperry@attbi.com
Thu Feb 6 20:22:03 2003


On Thursday 06 February 2003 05:23, Erik Price wrote:
> On Thursday, February 6, 2003, at 12:20  AM, Sean 'Shaleh' Perry wrote:
> > easy answer: it has been that way since Python began.
> >
> > much of python lets you interact with objects without actually using
> > methods.
> > I think len() is one of those vestiges.
> >
> > I wonder if it had something to do with trying to ease people into OO
> > (Python
> > was meant to help those learning programming).
>
> Okay.  So there's nothing wrong with doing:
>
> class MyList():
>    def __init__(self):
>      self._mylist =3D []
>
>    def len(self):
>      return len(self)
>
> ?
>

return len(self._mylist) you mean

yes using has-a v. is-a would be a valid approach as well.

> It feels "dirty" to use the __init__ method since it has those magic
> underscores (I feel the same way about using if __name__ =3D=3D
> "__main__").  But there is no other name for the constructor, right?
>

the double underscore methods are needed to implement things.  You should=
 not=20
however see them in common, run of the mill code.

Things like __init__ are the way classes are designed and implemented.  Y=
ou=20
have no choice but to use them.  The __name__ =3D=3D "__main__" is indeed=
 a hack=20
but it has become a standard, expected idiom.