[Tutor] Properties of an object

Kent Johnson kent37 at tds.net
Fri Jan 30 23:16:27 CET 2009


On Fri, Jan 30, 2009 at 3:50 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> "spir" <denis.spir at free.fr> wrote
>
>> I was not thinking at data hiding or protection, rather at object
>> structure
>> (or behaviour) specification. First, to the human -- and alse to the
>> machine.
>
> Ah, OK, then in that case I am happier to agree that Python is unusual
> (although not unique - Lisp can do the same) in its ability to add new
> attributes - and even methods in V3 I believe - to an existing
> class/instance.

Python 2.x can add new methods to a user-defined class or instance or
redefine existing methods. Ruby and Objective-C also allow adding
methods to existing classes. In Python this is called
"monkey-patching" and considered a bad idea. In Ruby it is considered
a powerful feature and IIUC it is widely used.

> Indeed it's perfectly valid to do:
>
> class Data: pass   ## no attributes or methods!
>
> d1 = Data()
> d2 = Data()
>
> d1.foo = 'something'
> d2.bar = 66

Also this:
In [6]: def sayFoo(self): print 'foo'

In [7]: Data.sayFoo = sayFoo

In [8]: d1.sayFoo()
foo

> Actually Lisp goes further than Python and allows us to switch
> inherited classes around in the method resolution lookup etc
> at run time, so
>
> (foo myMethod)
>
> might call different methods at different places in the same
> program (don't do this kiddies, it will make your brain hurt!)

With old-style classes, you can assign directly to __bases__. This
seems to have been removed for new-style classes.

>> there is no real object specification; not even by class:

The introduction of Abstract Base Classes in Python 2.6 and 3.0 seems
intended to remedy this, giving you a way to specify an interface in
the language:
http://docs.python.org/whatsnew/2.6.html#pep-3119-abstract-base-classes

Kent


More information about the Tutor mailing list