Classes as objects
Ken Seehof
kens at sightreader.com
Thu Apr 26 19:27:04 EDT 2001
"Daniel Klein" <DanielK at jBASE.com> wrote:
> Haven't posted for a while but I this time I am requesting some
assistence.
>
> I'm putting on a presentation on the benefits of Python over Java and one
of
> the points I would like to make is how everything is an object, even
> Classes. Can anyone out there in PythonVille provide a simple (practical)
> example of how classes can be used as objects?
>
> Thanks,
> Daniel Klein
Here's a debugging hack that messes with classes:
class Eyeball:
def __setattr__(self, a, v):
k = self.__class__.__bases__[1]
print "<%s: %s = %s>" % (k.__name__, a, `v`)
if hasattr(k, '__setattr__'):
k.__setattr__(self, a, v)
else:
self.__dict__[a] = v
def watch(x):
class E: pass
E.__bases__ = (Eyeball, x.__class__)
E.__name__ = 'Eyeball_%s' % x.__class__.__name__
x.__class__ = E
def unwatch(x):
try:
e,k = x.__class__.__bases__
except:
e=None
if e!=Eyeball:
raise TypeError, 'not a watched instance'
x.__class__ = k
>>> class Q:
... pass
...
>>> q = Q()
>>> q.spam = 12
>>> watch(q)
>>> q.spam = 23
<Q: spam = 23>
>>> unwatch(q)
>>> q.qpam = 34
>>>
Of course, this can get much more fancy. For example, I have
a version that writes all method calls on any instance object to
a log file.
- Ken Seehof kseehof at neuralintegrator.com
More information about the Python-list
mailing list