metaclass & __slots__

Holden Caulfield phoebe_1 at att.net
Wed Jul 3 17:17:58 EDT 2002


Greetings,
  I am trying to get a hang of the metaclass and some new features in
v2.2. But, I am running into a problem or it is a limitation, I guess.
I just need clarification. Here is the code, it is an extension of
Guido's autoprop example.
Basically, I am trying to set "property" attributes AND also limit the
attributes set by using "__slots__".

It looks like because the Metalcass statement is executed in the end
of the class statement, hence the class methods seems to have a
"early" binding to the __slots__ variable. Is this behaviour normal?

Thanks
M

-----

class MX(type):
    def __init__(cls,name,bases,dict):
        super(MX,cls).__init__(name,bases,dict)
        props = {}
        slots = getattr(cls,'__slots__', [])
        print slots
        for v in dict.keys():
            vs = v.startswith
            if vs("_get_") or vs("_set_"):
                props[v[5:]] = 1
        for v in props.keys():
            fget = getattr(cls,"_get_%s" % v, None)
            fset = getattr(cls,"_set_%s" % v, None)
            setattr(cls,v,property(fget,fset))
        slots.append("_%s__%s" % (name,v))
        setattr(cls,'__slots__',slots) 

class X(object):
    __metaclass__ = MX
    __slots__ = ['z']
    def __init__(self):
        self.x = 1
        self.z = 2
    def _get_x(self):
        return self.__x
    def _set_x(self,v):
        self.__x = v

def Test():
    y = X()
    y.x = 4

if __name__ == "__main__": Test()

--------------
The above code fails with:
Traceback (most recent call last):
  File "__test.py", line 50, in ?
    if __name__ == "__main__": Test()
  File "__test.py", line 43, in Test
    y = X()
  File "__test.py", line 34, in __init__
    self.x = 1
  File "__test.py", line 39, in _set_x
    self.__x = v
AttributeError: 'X' object has no attribute '_X__x'



More information about the Python-list mailing list