Classes in Python
Michele Simionato
mis6 at pitt.edu
Fri Apr 18 17:08:11 EDT 2003
Bill Martin <wcmartin at vnet.net> wrote in message news:<3EA01A9B.4030209 at vnet.net>...
> I'm wondering about the value of allowing a class definition like this:
>
> class C:
> pass
>
> Now I can define a = c() and b = c(), then say a.x1 = 1.2, b.x2 = 3.5 or
> some such. If I try to print a.x2 or b.x1, I get an exception message
> basically saying those member variables don't exist. It seems to me this
> defeats one of the basic ideas behind OOP, that is to assign members to
> the class definition.
Some time ago I posted this recipe to make Python anal in the way you
want:
def frozen(self,name,value):
if hasattr(self,name):
object.__setattr__(self,name,value) # standard __setattr__
else:
raise AttributeError("You cannot add attributes to %s" % self)
class Frozen(object):
"""Subclasses of Frozen are frozen, i.e. it is impossibile to add
new attributes to them and their instances"""
__setattr__ = frozen
class __metaclass__(type):
__setattr__ = frozen
Cheers,
Michele
More information about the Python-list
mailing list