On Thu, Sep 19, 2002 at 09:20:13PM +0900, Vincent Foley wrote:
> But my friend told me that Python didn't have that because it was not a
> good thing and it was not the proper way to do it.  He said that the
> true way of doing it, is to subclass (since Python 2.2 can now subclass
> builtin types) the base class:

1) He is right that adding methods to an already-defined class is
   generally a bad idea.  There are some valid reasons to do that, but
   99% of the time there is an alternative.

   Subclassing is one such alternative.  Extending an instance of a
   class is another alternative.  Creating a new method that takes your
   object as an explicit parameter instead of as an implicit parameter
   is a third alternative.

2) Correct me if I'm wrong, but I think python does let you add methods
   at run-time:

   [pbrannan@zaphod pbrannan]$ python
   Python 2.2.1c2 (#1, Apr  8 2002, 18:12:08) 
   [GCC 3.0.4] on linux2
   Type "help", "copyright", "credits" or "license" for more information.
   >>> class Foo:
   ...   def foo(self):
   ...     print "foo!"
   ... 
   >>> f = Foo()
   >>> f.foo()
   foo!
   >>> f.bar()
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
   AttributeError: Foo instance has no attribute 'bar'
   >>> def bar(self):
   ...   print "bar!"
   ... 
   >>> Foo.__dict__['bar'] = bar
   >>> f.foo()
   foo!
   >>> f.bar()
   bar!

Paul