Help setting default class attributes

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Thu Sep 6 13:56:33 EDT 2007


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





More information about the Python-list mailing list