python怎么创建和使用一个简单的元类
admin
2023-07-08 08:04:45
0

示例

#!/usr/bin/env python

# [SNIPPET_NAME: Simple metaclass]
# [SNIPPET_CATEGORIES: Python Core] 
# [SNIPPET_DESCRIPTION: Shows how to create a and use a simple metaclass]
# [SNIPPET_AUTHOR: Florian Diesch ]
# [SNIPPET_LICENSE: MIT]

# Copyright 2010 Florian Diesch 
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

class PropertyMetaclass(type):
    """ 
    This metaclass expects its instances to have a class attribute
    __properties__ that is a dict mapping property names to their
    default values. The metaclass creates the corresponding
    properties
    """

    def __init__(cls, name, bases, dict):
        type.__init__(cls, name, bases, dict)

        props = getattr(cls, '__properties__', {})
        for name, default in props.iteritems():
            type(cls).create_property(cls, name, default)

    def attr_name(cls, prop):
        """ returns the attribute name for property """
        return '_%s'%prop

    def create_property(cls, name, default):
        """ creates a property named  with default value """
        getter=cls.create_getter(name)
        setter=cls.create_setter(name)
        prop=property(getter, setter, None, None)

        # that's the attribute holding the actual value
        setattr(cls, cls.attr_name(name), default) 

        # that's the property
        setattr(cls, name, prop)

    def create_getter(cls, prop):
        """  creates a getter method for property """
        attr=cls.attr_name(prop)
        def getter(self):
            print "  class %s: get %s"%(cls.__name__, prop)
            return getattr(self, attr)
        return getter

    def create_setter(cls, prop):
        """  creates a setter method for property """
        attr=cls.attr_name(prop)
        def setter(self, value):
            print "  class %s: set %s to '%s'"%(cls.__name__, prop, value)
            setattr(self, attr, value)
        return setter

class Book(object):
    __metaclass__= PropertyMetaclass  # use the metaclass

    __properties__ = {  # some properties
        'author': '[unknown title]',
        'title': '[unknown author]'
        }

if __name__ == '__main__':
    book = Book()
    print '%s by %s'%(book.title, book.author)
    book.author = 'Euclid'
    book.title = 'Elements'
    print '%s by %s'%(book.title, book.author)

    # prints:
    #
    #   class Book: get title
    #   class Book: get author
    # --unknown author-- by --unknown title--
    #   class Book: set author to 'Euclid'
    #   class Book: set title to 'Elements'
    #   class Book: get title
    #   class Book: get author
    # Elements by Euclid

相关内容

热门资讯

我国科学家为细胞信号“导航”开... 新华社济南5月31日电(记者张力元)人体细胞犹如一座精密的通信城市,每天都有大量“指令”穿梭传递,调...
极端大风突袭哈尔滨!过山车停摆... 极目新闻记者 詹钘5月31日,受强对流天气影响,哈尔滨国际会展中心体育场相关设施受到损坏,原计划当晚...
三原电缆取得电缆接头连接用防护... 国家知识产权局信息显示,上海三原电缆附件有限公司取得一项名为“一种电缆接头连接用防护结构”的专利,授...
原创 识... 还是那句话,机圈苦大屏久已…… 虽然大屏有大屏的美,但是小屏也有小屏的俏。在大屏旗舰占据主流的手机市...
玄戒技术取得分频电路专利,实现... 国家知识产权局信息显示,北京玄戒技术有限公司取得一项名为“分频电路、分频器、射频芯片和电子设备”的专...
为什么今年香会基调明显变了 5月29日—31日在新加坡举行的第23届香格里拉对话会(简称“香会”),见证着元首引领下大国关系继续...
成本几毛钱、假驱蚊液香精兑水,... 入夏升温,蚊虫进入活跃期,驱蚊防护成为民生刚需,《财经调查》持续接到消费者投诉,他们买到的多款网红驱...
越来越多80后90后,正在丧失... 六一儿童节到来之际,朋友圈里开始出现一种熟悉的热闹。有人晒出零食礼包,有人半开玩笑地向伴侣讨礼物,还...
洋保电子取得用于低温环境的电气... 国家知识产权局信息显示,洋保电子(太仓)有限公司取得一项名为“一种用于低温环境的电气柜”的专利,授权...
中日韩飞手争霸宁波!2026无... 潮新闻客户端 记者 陈冲 通讯员 朱凝 5月31日,2026小遛·无人机竞速世界杯(中国·宁波鄞州站...