[Tutor] Custom metaclass?
jmh at physics.ucdavis.edu
Thu Apr 19 22:31:20 CEST 2007
Greetings. I've been looking at O'Reilly's "Python Cookbook", 2nd
edition, just for my own edification. In particular, I'm looking at
chapter 6, "Object-Oriented Programming".
Recipe 6.3, "Restricting Attribute Setting", intends to solve the
problem that, by default, users can add and modify attributes of class
instances, or even classes themselves, as in the following example:
>>> class Foo(object): pass
>>> f = Foo()
>>> f.age = 42
>>> Foo.loc = 'Tralfamadore'
>>> g = Foo()
The approach, in essence, is a fairly standard one: redefine the
__setattr__ method to add some logic to enforce whatever restrictions
you choose, but the details are a bit convoluted. Copyright law
probably prohibits me from posting the entire recipe, but here's the
piece that leads to my question (see below):
""" subclasses of NoNewAttrs inhibit addition of new attributes,
while allowing existing attributed to be set to new values.
# block the addition new attributes to instances of this class
__setattr__ = no_new_attributes(object.__setattr__)
"simple custom metaclass to block adding new attrs to this class"
__setattr__ = no_new_attributes(type.__setattr__)
(Beware line breaks introduced by email software.)
Finally, my question: can somebody enlighten me as to how and why the
does something useful?
Michael Hannon mailto:hannon at physics.ucdavis.edu
Dept. of Physics 530.752.4966
University of California 530.752.4717 FAX
Davis, CA 95616-8677
More information about the Tutor