[Python-Dev] None as a keyword / class methods

Donald Beaudry Donald Beaudry <donb@init.com>
Tue, 28 Mar 2000 15:46:06 -0500


...sorry to jump in on the middle of this one, but.

A while back I put a lot of thought into how to support class methods
and class attributes.  I feel that I solved the problem in a fairly
complete way though the solution does have some warts.  Here's an
example:

>>> class foo(base):
...     value = 10 # this is an instance attribute called 'value'
...                # as usual, it is shared between all instances
...                # until explicitly set on a particular instance
... 
...     def set_value(self, x):
...         print "instance method"
...         self.value = x
... 
...     #
...     # here come the weird part
...     #
...     class __class__:
...         value = 5  # this is a class attribute called value
... 
...         def set_value(cl, x):
...             print "class method"
...             cl.value = x
... 
...         def set_instance_default_value(cl, x):
...             cl._.value = x
...
>>> f = foo()
>>> f.value
10
>>> foo.value = 20
>>> f.value
10
>>> f.__class__.value
20
>>> foo._.value
10
>>> foo._.value = 1
>>> f.value
1
>>> foo.set_value(100)
class method
>>> foo.value
100
>>> f.value
1
>>> f.set_value(40)
instance method
>>> f.value
40
>>> foo._.value
1
>>> ff=foo()
>>> foo.set_instance_default_value(15)
>>> ff.value
15
>>> foo._.set_value(ff, 5)
instance method
>>> ff.value
5
>>>


Is anyone still with me?

The crux of the problem is that in the current python class/instance
implementation, classes dont have attributes of their own.  All of
those things that look like class attributes are really there as
defaults for the instances.  To support true class attributes a new
name space must be invented.  Since I wanted class objects to look
like any other object, I chose to move the "instance defaults" name
space under the underscore attribute.  This allows the class's
unqualified namespace to refer to its own attributes.  Clear as mud,
right?

In case you are wondering, yes, the code above is a working example.
I released it a while back as the 'objectmodule' and just updated it
to work with Python-1.5.2.  The update has yet to be released.

--
Donald Beaudry                                     Ab Initio Software Corp.
                                                   201 Spring Street
donb@init.com                                      Lexington, MA 02421
                      ...Will hack for sushi...