__dict__s and types and maybe metaclasses...

Larry Bates larry.bates at websafe.com
Wed May 2 17:24:27 EDT 2007


Adam Atlas wrote:
> Suppose I want to create a type (i.e. a new-style class via the usual
> `class blah(...)` mechanism) but, during the process of creating the
> type, I want to replace its __dict__ so I can override some behaviors
> during the initial assignment of its members. That is, I have `class
> blah(...): a = 123; b = 456; ...`, and I want to substitute my own
> dict subclass which will thus receive __setitem__(a, 123),
> __setitem__(b, 456), and so on.
> 
> Is this possible? Maybe with metaclasses? I've experimented with them
> a bit, but I haven't found any setup that works.
> 

I think that most people accomplish this by:

class blah:
    __initial_values={'a': 123, 'b': 456}

    def __init__(self):
        self.__dict__.update(self.__initialvalues)

-Larry



More information about the Python-list mailing list