2.2 properties and subclasses

Just just at xs4all.nl
Tue May 20 03:53:09 EDT 2003


In article <slrnbcj414.vot.miles at car.pixar.com>,
 Miles Egan <miles at rddac.com> wrote:

> Repeating the property declaration for every property becomes painful
> when you have a dozen classes with 10 properties each.  There's
> already a fair amount of boilerplate you have to write to set the
> properties up in the base class.

You could write a metaclass that automatically creates properties (say 
using a naming convention):

class AutoProperty(type):
    def __new__(cls, name, bases, methoddict):
        for key, value in methoddict.items():
            if key.startswith("get_"):
                methoddict[key[4:]] = property(value)
        return type.__new__(cls, name, bases, methoddict)


class Base(object):
    
    __metaclass__ = AutoProperty
    
    def get_foo(self):
        return "BASE"


class Sub(Base):

    def get_foo(self):
        return "SUB"


b = Base()
print b.foo
s = Sub()
print s.foo


Just




More information about the Python-list mailing list