setattr in class

Arnaud Delobelle arnodel at googlemail.com
Fri Sep 12 22:59:49 CEST 2008


On Sep 12, 4:30 pm, Bojan Mihelac <bmihe... at gmail.com> wrote:
> On Sep 12, 5:21 pm, Christian Heimes <li... at cheimes.de> wrote:
>
> > Bojan Mihelac wrote:
> > > I guess A class not yet exists in line 4. Is it possible to achive
> > > adding dynamic attributes without using exec?
>
> > Correct, the class doesn't exist until the end of the class body. You
> > can either do it outside the class definition or you can use a metaclass.
>
> > Christian
>
> thanks, can you give example on using a metaclass?

class MoreMeta(type):
    def __init__(self, name, bases, attrs):
        more = attrs.get('moreattrs')
        if more:
            for attr, val in more.iteritems():
                setattr(self, attr, val)

class MoreObject(object):
    __metaclass__ = MoreMeta

class A(MoreObject):
    moreattrs = {}
    for i in '12':
        moreattrs['title_' + i] = int(i)

>>> A.title_1
1
>>> A.title_2
2
>>>

--
Arnaud




More information about the Python-list mailing list