Overriding methods in classes that use property()

Thomas Heller theller at python.net
Mon Apr 22 14:39:58 EDT 2002


"Edmund Lian" <elian at inbrief.net> wrote in message news:mailman.1019488863.14978.python-list at python.org...
> Hi,
>
> When I run the code appended below, class B inherits all the methods of
> class A, including the property() definition as I would expect.
> Unfortunately, class C also does the same; I cannot override class A's
> setVal method. Is this a bug, or do I have to do something different (and
> unexpected) with Python 2.2's new style classes?
>
> ...Edmund.
>
> class A(object):
>     def __init__(self):
>         self._val = None
>
>     def setVal(self, value):
>         self._val = value
>
>     def getVal (self):
>         return self._val
>
>     val = property(getVal, setVal)
>
> class B(A):
>     pass
>
> class C(A):
>     def setVal(self, value):
>         self._val = 'Huh?'
>
You can achive what you want with a metaclass, see code below.
Every time a new subclass of A is created, the __metaclass__
__init__ method is called, which retrieves the correct
getVal and setVal methods, and creates a property from them:

class A(object):
    class __metaclass__(type):
        def __init__(cls, name, bases, dict):
            cls.val = property(cls.getVal, cls.setVal)

    def __init__(self):
        self._val = None

    def setVal(self, value):
        self._val = value

    def getVal (self):
        return self._val

class B(A):
    pass

class C(A):
    def setVal(self, value):
        self._val = 'Huh?'


Regards,

Thomaas





More information about the Python-list mailing list