[Python] 演示python如何创建和使用一个简单的元类 →→→→→进入此内容的聊天室

来自 , 2020-03-11, 写在 Python, 查看 95 次.
URL http://www.code666.cn/view/0e795480
  1. #!/usr/bin/env python
  2. #-*- coding: utf-8-*-
  3.  
  4. # [SNIPPET_NAME: Simple metaclass]
  5. # [SNIPPET_CATEGORIES: Python Core]
  6. # [SNIPPET_DESCRIPTION: Shows how to create a and use a simple metaclass]
  7. # [SNIPPET_AUTHOR: Florian Diesch <diesch@spamfence.net>]
  8. # [SNIPPET_DOCS: http://www.ibm.com/developerworks/linux/library/l-pymeta.html]
  9. # [SNIPPET_LICENSE: MIT]
  10.  
  11. # Copyright 2010 Florian Diesch <diesch@spamfence.net>
  12. # All rights reserved.
  13. #
  14. # Permission is hereby granted, free of charge, to any person obtaining a copy
  15. # of this software and associated documentation files (the "Software"), to deal
  16. # in the Software without restriction, including without limitation the rights
  17. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18. # copies of the Software, and to permit persons to whom the Software is
  19. # furnished to do so, subject to the following conditions:
  20. #
  21. # The above copyright notice and this permission notice shall be included in
  22. # all copies or substantial portions of the Software.
  23. #
  24. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  25. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  26. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  27. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  28. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  29. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  30. # THE SOFTWARE.
  31. #
  32.  
  33. class PropertyMetaclass(type):
  34.     """
  35.    This metaclass expects its instances to have a class attribute
  36.    __properties__ that is a dict mapping property names to their
  37.    default values. The metaclass creates the corresponding
  38.    properties
  39.    """
  40.  
  41.     def __init__(cls, name, bases, dict):
  42.         type.__init__(cls, name, bases, dict)
  43.  
  44.         props = getattr(cls, '__properties__', {})
  45.         for name, default in props.iteritems():
  46.             type(cls).create_property(cls, name, default)
  47.  
  48.  
  49.     def attr_name(cls, prop):
  50.         """ returns the attribute name for property <prop>"""
  51.         return '_%s'%prop
  52.  
  53.    
  54.     def create_property(cls, name, default):
  55.         """ creates a property named <name> with default value <default>"""
  56.         getter=cls.create_getter(name)
  57.         setter=cls.create_setter(name)
  58.         prop=property(getter, setter, None, None)
  59.  
  60.         # that's the attribute holding the actual value
  61.         setattr(cls, cls.attr_name(name), default)
  62.        
  63.         # that's the property
  64.         setattr(cls, name, prop)
  65.  
  66.  
  67.     def create_getter(cls, prop):
  68.         """  creates a getter method for property <prop>"""
  69.         attr=cls.attr_name(prop)
  70.         def getter(self):
  71.             print "  class %s: get %s"%(cls.__name__, prop)
  72.             return getattr(self, attr)
  73.         return getter
  74.  
  75.     def create_setter(cls, prop):
  76.         """  creates a setter method for property <prop>"""
  77.         attr=cls.attr_name(prop)
  78.         def setter(self, value):
  79.             print "  class %s: set %s to '%s'"%(cls.__name__, prop, value)
  80.             setattr(self, attr, value)
  81.         return setter
  82.  
  83.  
  84. class Book(object):
  85.     __metaclass__= PropertyMetaclass  # use the metaclass
  86.  
  87.     __properties__ = {  # some properties
  88.         'author': '[unknown title]',
  89.         'title': '[unknown author]'
  90.         }
  91.  
  92.  
  93. if __name__ == '__main__':
  94.     book = Book()
  95.     print '%s by %s'%(book.title, book.author)
  96.     book.author = 'Euclid'
  97.     book.title = 'Elements'
  98.     print '%s by %s'%(book.title, book.author)
  99.  
  100.     # prints:
  101.     #
  102.     #   class Book: get title
  103.     #   class Book: get author
  104.     # --unknown author-- by --unknown title--
  105.     #   class Book: set author to 'Euclid'
  106.     #   class Book: set title to 'Elements'
  107.     #   class Book: get title
  108.     #   class Book: get author
  109.     # Elements by Euclid
  110. #//python/2371

回复 "演示python如何创建和使用一个简单的元类"

这儿你可以回复上面这条便签

captcha