Can I create class properties during __new__ or __init__?

Posted by 007brendan on Stack Overflow See other posts from Stack Overflow or by 007brendan
Published on 2010-03-23T01:19:59Z Indexed on 2010/03/23 1:21 UTC
Read the original article Hit count: 225

Filed under:

I want to do something like this. The _print_attr function is designed to be called lazily, so I don't want to evaluate it in the init and set the value to attr. I would like to make attr a property that computes _print_attr only when accessed:

class Base(object):
    def __init__(self):
        for attr in self._edl_uniform_attrs:
            setattr(self, attr, property(lambda self: self._print_attr(attr)))

    def _print_attr(self, attr):
        print attr


class Child(Base):
    _edl_uniform_attrs = ['foo', 'bar']


me = Child()
me.foo
me.bar

#output:
#"foo"
#"bar"

© Stack Overflow or respective owner

Related posts about python