Can I create class properties during __new__ or __init__?

前端 未结 4 1044
忘了有多久
忘了有多久 2021-01-18 23:52

I want to do something like this, but I haven\'t had much success so far. I would like to make each attr a property that computes _lazy_eval only when accessed:

<         


        
4条回答
  •  花落未央
    2021-01-19 00:10

    Technically you want a metaclass:

    class LazyMeta(type):
        def __init__(cls, name, bases, attr):
            super(LazyMeta, cls).__init__(name, bases, attr)
            def prop( x ):
                return property(lambda self: self._lazy_eval(x))
            for x in attr['lazyattrs']:
                setattr(cls, x, prop(x))
    
    class Base(object):
        __metaclass__ = LazyMeta
        lazyattrs = []
        def _lazy_eval(self, attr):
            #Do complex stuff here
            return attr
    
    class Child(Base):
        lazyattrs = ['foo', 'bar']
    
    me = Child()
    
    print me.foo
    print me.bar
    

提交回复
热议问题