[Tutor] Re: slots - a more basic issue
Lloyd Kvam
pythontutor@venix.com
Fri, 05 Jul 2002 10:07:17 -0400
We've been concerned about attribute name errors for our Record classes
which tie back to database tables. Our solution was to have a class
attribute named fieldlist with the list of fields from the associated
database table. Then we used __getattr__, __setattr__, and __delattr__
to enforce the requirement that all attributes had to be listed in the
class's fieldlist. This avoids doing special handling elsewhere in the
class methods.
Here is a simplified example where the fieldlist is wired into the class
definition. This approach may work for you.
class Example(object):
fieldlist = ('a','b','c')
def __getattr__(self, key):
if key in self.fieldlist: # provide default value of None
return None
else:
raise AttributeError("%s is not an attribute of this object" % key)
def __setattr__(self, key, value):
if key in self.fieldlist:
self.__dict__[key] = value
else:
raise AttributeError("%s is not an attribute of this object" % key)
def __delattr__(self, key):
raise AttributeError( "Attribute %s must not be deleted" % key)
I gave this some light testing and it seemed to work. HTH.
Arthur Siegel wrote:
> Dman writes -
>
>
>>Use a method signature such as :
>> def __init__(self, x, y, color=None ):
>>and you'll get :
>>
>
>>Traceback (most recent call last):
>> File "<stdin>", line 1, in ?
>>TypeError: __init__() got an unexpected keyword argument 'kolor'
>>
>
> Yeah, but I have lots of potential attributes, and lots
> of inheritance relationships - which makes the method signature
> unwieldy - just what **kw seems to be made for.
>
> Looks like I'll end up with building a list of attributes and something
> like:
>
> for key in kws:
> if key not in optlist:
> print 'WARNING " %s" not a valid keyword for %s'
> %(key,self.__class__.__name__)
>
> Just found a bunch of typos in my demos doing this approach.
>
> Art
>
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice:
603-443-6155
fax:
801-459-9582