随笔 - 41, 文章 - 8, 评论 - 8, 引用 - 0
数据加载中……

[导入][python]使用metaclass自动生成set/get方法

在python cookbook的Chapter 20的 Introduction中,有关于metaclass(元类)的简单介绍,它自动生成了以一个下划线带头的get方法。

我改进了一下,使其也具有set方法,当然就是增加了几行代码。

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
>>>

可以看到,Point __slot__ 中放入x,y,z三个名字,然后就自动生成类似getx,setx的方法。

metaclass 真是强大啊。

阅读全文
类别:Python 查看评论
文章来源:http://hi.baidu.com/mirguest/blog/item/a33c7d5314d7ca0b377abe68.html

posted on 2011-02-02 12:01 mirguest 阅读(1856) 评论(0)  编辑 收藏 引用 所属分类: python


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理