Help setting default class attributes
Steve Holden
steve at holdenweb.com
Thu Sep 6 14:47:36 EDT 2007
attn.steven.kuo at gmail.com wrote:
> On Sep 6, 10:26 am, rh0dium <steven.kl... at gmail.com> wrote:
>> Hi all,
>>
>> I have the following piece of code and I wanted to set the default
>> attributes based on a dictionary. What I am looking for is a way to
>> take PIPODEFAULTS and assign each one as an attribute for the class
>> pipo. Can someone show me how to do this by iterating over the
>> PIPODEFAULTS and assign them. What I would expect to be able to do is
>> call the class and modify them.
>>
>> example:
>> a = pipo()
>> print a.caseSensitivity
>> "preserve"
>>
>> a.caseSensitivity = "lower"
>> print a.caseSensitivity
>> "lower"
>>
>
>
> I infer from your example that you want
> to set default attributes for *instances of* class pipo
> (not for class pipo itself).
>
> Use setattr:
>
> class pipo(object):
> PIPODEFAULTS = {'caseSensitivity':'preserve',
> 'cellMapTable':'checkPolygon', # etc
> }
> def __init__(self, *args, **kwargs):
> for attr, value in pipo.PIPODEFAULTS.iteritems():
> setattr(self, attr, value)
>
> a = pipo()
> b = pipo()
> print a.caseSensitivity
> a.caseSensitivity = 'lower'
> print a.caseSensitivity
> print b.caseSensitivity
>
> --
> Hope this helps,
> Steven
>
>
This is actually way over-complicated. Remembering that the MRO will
look in the class to resolve the name of an attribute it doesn't find in
the instance you can simply use the class as a repository for the defaults:
>>> class pipo(object):
... caseSensitivity = 'preserve'
... cellMapTable = 'checkPolygon'
... # ...
...
>>> p1 = pipo()
>>> p2 = pipo()
>>> p1.caseSensitivity
'preserve'
>>> p2.caseSensitivity = "lower"
>>> p1.caseSensitivity
'preserve'
>>> p2.caseSensitivity
'lower'
>>>
You could extend the class to allow per-instance defaults to be set in
the __init__() method too (untested):
class pipo(object):
caseSensitivity = "preserve"
cellMapTable = 'checkPolygon'
def __init__(self, ..., **kw):
self.__dict__.update(kw)
p1 = pipo(caseSensitivity='lower')
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------
More information about the Python-list
mailing list