Favorite non-python language trick?
Bernhard Herzog
bh at intevation.de
Sat Jul 2 13:55:15 EDT 2005
Scott David Daniels <Scott.Daniels at Acm.Org> writes:
> Rocco Moretti wrote:
>> Joseph Garvin wrote:
>>
>> I'm not aware of a language that allows it, but recently I've found
>> myself wanting the ability to transparently replace objects....
>> I mainly look for it in the "object replaces self" form, but I guess
>> you could also have it for arbitrary objects, e.g. to wrap a logging
>> object around a function, even if you don't have access to all
>> references of that function.
>> Why isn't it in Python? It's completely counter to the conventional
>> object semantics.
>
> Actually this is the old (and terrifying) Smalltalk message 'becomes:'.
> There is a concrete reason it is not in python: objects are represented
> as pointers to their data structures, do not have identical sizes, and
> therefore cannot be copied into each others data space.
That limitation applies only some of the time, e.g. when you inherit
from built-in types. But for ordinary classes it can be done:
>>> class A(object):
... def __init__(self, x):
... self.x = x
...
>>> class B(object):
... def __init__(self, y):
... self.y = y
...
>>> a = A(1)
>>> b = B(2)
>>> vars(a)
{'x': 1}
>>> vars(b)
{'y': 2}
>>> a.__class__, b.__class__ = b.__class__, a.__class__
>>> a.__dict__, b.__dict__ = b.__dict__, a.__dict__
>>> vars(a)
{'y': 2}
>>> isinstance(a, B)
True
Bernhard
--
Intevation GmbH http://intevation.de/
Skencil http://skencil.org/
Thuban http://thuban.intevation.org/
More information about the Python-list
mailing list