Python's Lisp heritage

Paul Foley see at below
Sun Apr 28 23:08:38 EDT 2002


On Sun, 28 Apr 2002 13:18:49 -0600, Andrew Dalke wrote:

> I'm not sure what your point is here.  In more recent Pythons (1.5 and
> newer, I think) you can do

> >>> class Spam:
> ...  def what(self): print "I'm spam"
> ...
> >>> class Eggs:
> ...  def what(self): print "I'm eggs"
> ...
> >>> x = Spam()
> >>> x.what()
> I'm spam
> >>> x.__class__ = Eggs
> >>> x.what()
> I'm eggs

OK, but now try this:

  _spams = WeakList()
  _eggs = WeakList()
  
  class Spam:
     def __init__(self):
         self.y = 42
         _spams.append(self)

  class Eggs:
     def __init__(self):
         self.z = 17
         _eggs.append(self)

  x = Spam()
  x.__class__ = Eggs


Problems: x.z isn't present, x.y is present but unwanted, and the
instance is a member of _spams, not of _eggs.

You changed the class, but you didn't do anything to ensure that the
object is actually a _valid_ instance of the new class.

In CL, (change-class x 'eggs) can do whatever needs to be done to make
x into a valid egg (there are various generic functions invoked along
the way that you can write methods on to make it do the right thing;
the main one being update-instance-for-different-class, which chooses
the appropriate method to run based on both the old and new classes)

-- 
In modern physics, the more logical you are, the more wrong you are.
                                                           -- Lama Govinda
(setq reply-to
  (concatenate 'string "Paul Foley " "<mycroft" '(#\@) "actrix.gen.nz>"))



More information about the Python-list mailing list