[Python-3000] State of the object system
Michael Chermside
mcherm at mcherm.com
Fri May 26 12:46:49 CEST 2006
On 5/18/06, Kay Schluehr <kay.schluehr at gmx.net> wrote:
> Michael Chermside schrieb:
>
> >Unfortunately, for implementation reasons you can't modify most
> >built-in (and some user-defined) classes in this fashion:
> >
> > >>> int.func2 = func2
> >
> > Traceback (most recent call last):
> > File "<pyshell#35>", line 1, in -toplevel-
> > int.func2 = func2
> > TypeError: can't set attributes of built-in/extension type 'int'
> >
> >Most Python programmers would probably agree that this is a
> >perfectly fine restriction. Built-in classes like int and dict
> >are widely used... allowing the code from any one module to
> >modify them has dangerously non-local effects.
> >
> And that's not true for user defined classes?
No, it's now. I suspect (this is just a wild guess) that more than half
of all Python modules use int somewhere. I'm guessing nearly
100% use str, and I'm certain 100% use dict. That's just not true
of user defined classes, not even widely used libraries.
> Adding a
> method isprime() or iseven() to a subclass of int will suddenly be lost
> in the resulting object after an operation as long as it is not
> overwritten to return the right type and not the base type. So it is
> questionable if subclassing is really a good design decision.
That's why int subclasses can override both __add__ and __radd__
to ensure that your subclass is returned when combined with normal
ints. But I agree that it's not a good decision... making "isprime()" or
"iseven()" a helper function (not method) is probably a better design.
> AFAIK Ruby doesn't support standalone functions but needs a class
> context to define them as methods. Python might be more liberal in this
> respect but it seems to me that it forces to write functions in certain
> situations.
Yes it is, and while it doesn't *force* you to write functions, if what you
want is really a function, then why work to make it a method? (See Java.)
> Sometimes a broken structure needs more justification than a sound one.
> Arbitrary restrictions complicate the language semantics for no good
> reasons. But if it is strongly encouraged not to add methods to classes
> at runtime we might get rid of the self parameter that lessens the
> barrier between functions and methods?
The barrier between functions and methods is QUITE small in Python,
and the existance of the self parameter is the major reason for this. A
method is just a funciton in which we happen to pass an object instance
as the first argument. (Bound methods are slightly different beasts.) So
I'm not sure what you're suggesting here.
- Michael Chermside
More information about the Python-3000
mailing list