Concrete classes -- stylistic question

Michael Hudson mwh at python.net
Thu Oct 10 13:23:56 EDT 2002


Andrew Koenig <ark at research.att.com> writes:

> On a few occasions I've wanted to define ``concrete classes'' --
> classes that are so simple that their structure is their interface.
> For example, I might want a little class to hold (x, y) pairs.

I was bored, so I wrote this:

/>> class typed_property(object):
|..     def __init__(self, type, name):
|..         self.type = type
|..         self.name = name
|..     def __get__(self, ob, obclass):
|..         return getattr(ob, '%s_value'%self.name)
|..     def __set__(self, ob, value):
|..         if not isinstance(value, self.type):
|..             raise TypeError, "'%s' should be %r, not %r"%(self.name, 
|..                                               self.type, type(value))
|..         setattr(ob, "%s_value"%self.name, value)
|..     def __delete__(self):
|..         delattr(ob, "%s_value"%self.name)
\__ 
/>> def TypedBunch(name, bases, ns):
|..     our_ns = {}
|..     propnames = [k for k in ns if not k.startswith('_')]
|..     for k in propnames:
|..         our_ns[k] = typed_property(ns[k], k)
|..     our_ns['__slots__'] = propnames + ['%s_value'%k for k in propnames]
|..     return type(name, bases, our_ns)
\__ 
/>> class XY:
|..     __metaclass__ = TypedBunch
|..     x = int
|..     y = (int, float)
\__ 
->> xy = XY()
->> xy.x = 1
->> xy.y = 1.1
->> xy.z = 1
Traceback (most recent call last):
  File "<input>", line 1, in ?
AttributeError: 'XY' object has no attribute 'z'
->> xy.x
1
->> xy.x = "abc"
Traceback (most recent call last):
  File "<input>", line 1, in ?
  File "<input>", line 9, in __set__
TypeError: 'x' should be <type 'int'>, not <type 'str'>
->> 

Not sure it's useful, but it was fun :)

Hmm, the __delete__ method looks broken.  Oh well.

Cheers,
M.

-- 
  MARVIN:  What a depressingly stupid machine.
                    -- The Hitch-Hikers Guide to the Galaxy, Episode 7



More information about the Python-list mailing list