然后我改写了下:
IDLE 2.6.5
>>> class M(type):
def __new__(cls, name, bases, classdict):
for attr in classdict.get('__slots__', ( )):
if attr.startswith('_'):
def getter(self, attr=attr):
return getattr(self, attr)
def setter(self, val=0, attr=attr):
return setattr(self, attr, val)
classdict['get' + attr[1:]] = getter
classdict['set' + attr[1:]] = setter
return type.__new__(cls, name, bases, classdict)
>>> class Point(object):
__metaclass__ = M
__slots__ = ['_x', '_y' ,'_z']
>>> p=Point()
>>> dir(p)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '_x', '_y', '_z', 'getx', 'gety', 'getz', 'setx', 'sety', 'setz']
>>> p.setx(10)
>>> p.getx()
10
>>>