[Tutor] Properties of an object

Eike Welk eike.welk at gmx.net
Sat Jan 31 00:17:06 CET 2009


Hello Spir!

On Friday 30 January 2009, spir wrote:
> In a rather consistent approach, Python does not provide any
> standard way to simply define/describe/structure an object -- or a
> class.
The added flexibility of Python gives great powers to the programmers 
of libraries. 


There is for example a library for Java/C++ style data attributes in 
Python; Traits:
http://code.enthought.com/projects/traits/docs/html/traits_user_manual/intro.html


Also pretty cool is the possibility to change what happens when you 
type the 'class' statement. You only have to define the global 
variable '__metaclass__', which must point to an alternative 
implementation of the class definition algorithm. It seems to be 
possible to write this algorithm in pure Python.
Some documentation is here:
http://www.python.org/download/releases/2.2/descrintro/#metaclasses
http://www.python.org/doc/essays/metaclasses/

This is a class definition algorithm (a metaclass) written in Python:
http://www.python.org/doc/essays/metaclasses/Meta.py


You can even change the type of an object at runtime:
----
In [1]:class A(object):
   .1.:    def f(self):
   .1.:        print 'A.f; self:', id(self)
   .1.:

In [2]:class B(object):
   .2.:    def f(self):
   .2.:        print 'B.f; self:', id(self)
   .2.:

In [3]:a = A()

In [4]:a.f()
A.f; self: 26272592

In [7]:a.__class__ = B

In [8]:a.f()
B.f; self: 26272592
-----


Kind regards,
Eike.


More information about the Tutor mailing list