Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

add examples

  • Loading branch information...
commit e3ebfdf6105a7566f49a328cc8602e554153ef62 1 parent 61a84f1
@hychen authored
View
17 source/_posts/2012-06-12-slide-pycontw2012.markdown
@@ -13,3 +13,20 @@ that why we use/don't use it.
the slide is here:
<div style="width:425px" id="__ss_13273962"> <strong style="display:block;margin:12px 0 4px"><a href="http://www.slideshare.net/hychen/what-can-meta-class-do-for-you-pycon-taiwan-2012" title="What can meta class do for you? @PyCon Taiwan 2012" target="_blank">What can meta class do for you? @PyCon Taiwan 2012</a></strong> <iframe src="http://www.slideshare.net/slideshow/embed_code/13273962" width="425" height="355" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="border:1px solid #CCC;border-width:1px 1px 0" allowfullscreen></iframe> <div style="padding:5px 0 12px"> View more <a href="http://www.slideshare.net/" target="_blank">presentations</a> from <a href="http://www.slideshare.net/hychen" target="_blank">HsinYi Chen</a> </div> </div>
+
+# Example Codes
+
+## Singleton
+{% include_code metaclass_Singleton.py %}
+
+## Countable
+{% include_code metaclass_countable.py %}
+
+## Class Verification
+{% include_code metaclass_verification.py %}
+
+## Delegation
+{% include_code metaclass_delegation.py %}
+
+## Logged
+{% include_code metaclass_logged.py %}
View
54 source/downloads/code/metaclass_countable.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2012 Hsin-Yi Chen
+
+# Author(s): Hsin-Yi Chen <ossug.hychen@gmail.com>
+
+# 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.
+
+# Goal: Class knows the count of its instances.
+
+# metaclass
+class Countable(type):
+
+ def __new__(mbs, name, bases, dct):
+ cls = type.__new__(mbs, name, bases, dct)
+ cls.count = 0
+ return cls
+
+ def __call__(cls, *args, **kwargs):
+ cls.count += 1
+ type.__call__(cls, *args, **kwargs)
+
+
+# class
+class Book(object):
+ __metaclass__ = Countable
+
+ def __init__(self, title):
+ self.title = title
+
+# run
+print 'I have {} books'.format(Book.count)
+a=Book('A1')
+b=Book('A2')
+c=Book('A3')
+d=Book('A4')
+print 'I have {} books'.format(Book.count)
View
56 source/downloads/code/metaclass_delegation.py
@@ -0,0 +1,56 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2012 Hsin-Yi Chen
+
+# Author(s): Hsin-Yi Chen <ossug.hychen@gmail.com>
+
+# 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 Delegated(type):
+
+ def __new__(mbs, name, bases, dct):
+ cls = type.__new__(mbs, name, bases, dct)
+ def myget(self, k):
+ return getattr(self.context, k)
+ def myset(self, k, v):
+ if not hasattr(self, 'context'):
+ self.__dict__['context'] = v
+ if k != 'context':
+ setattr(self.context, k, v)
+ cls.__getattr__ = myget
+ cls.__setattr__ = myset
+ return cls
+
+class Wrapper(object):
+ __metaclass__ = Delegated
+ def __init__(self, context):
+ self.context = context
+
+ def dump(self):
+ print 'the data is ' + repr(self.data)
+
+class Result(object):
+ def __init__(self, **kwargs):
+ self.__dict__.update(kwargs)
+
+result = Result(title='man ages', data=[1,2,3,4,5])
+wrap_result = Wrapper(result)
+wrap_result.dump()
+wrap_result.title = 'girl args'
+print result.title
View
72 source/downloads/code/metaclass_logged.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2012 Hsin-Yi Chen
+
+# Author(s): Hsin-Yi Chen <ossug.hychen@gmail.com>
+
+# 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.
+
+# Goal: Log informations to other places.
+def info(msg):
+ print 'info:'+msg
+def error(msg):
+ print 'error:'+msg
+
+import functools
+
+# To create a wrapped function
+def log(name, fn):
+ @functools.wraps(fn)
+ def wrap_fn(*args, **kwargs):
+ info('Enter func:{}'.format(name))
+ try:
+ ret = fn(*args, **kwargs)
+ except Exception, e:
+ error('Raised exception: {}'.format(e.message))
+ raise e
+ info('Got return value:{}'.format(ret))
+ info('Exit func:{}'.format(name))
+ return ret
+ return wrap_fn
+
+# Add logger decorator for each attr
+def add_logger(name, val):
+ return callable(val) and log(name, val) or val
+
+# Metaclass
+class Logged(type):
+
+ def __new__(mbs, name, bases, dct):
+ # if attr is callable log it.
+ dct = {k:add_logger(k, v) for k,v in dct.items()}
+ cls = type.__new__(mbs, name, bases, dct)
+ return cls
+
+# Class
+class Person(object):
+ __metaclass__ = Logged
+
+ def get(self):
+ return "I am get method"
+
+# Run!
+if __name__ == '__main__':
+ obj = Person()
+ obj.get()
View
50 source/downloads/code/metaclass_verification.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2012 Hsin-Yi Chen
+
+# Author(s): Hsin-Yi Chen <ossug.hychen@gmail.com>
+
+# 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.
+def check(cls, inf):
+ for attrname in inf.__dict__:
+ if attrname.startswith('__'):
+ continue
+ if not attrname in cls.__dict__.keys():
+ msg = 'ERROR: Can not find {} in {}'.format(attrname,
+ cls.__name__)
+ msg = msg.format(cls.__name__, inf.__name__, attrname)
+ print msg
+
+class JokeRequirement(object):
+ HaHaPoint = None
+
+class HasInterface(type):
+ def __new__(mbs, name, bases, dct):
+ interface = dct['__implemented__']
+ cls = type.__new__(mbs, name, bases, dct)
+ check(cls, interface)
+ return cls
+
+class JokeRequirement(object):
+ HaHaPoint = None
+
+class JokeInPTT(object):
+ __metaclass__ = HasInterface
+ __implemented__ = JokeRequirement
Please sign in to comment.
Something went wrong with that request. Please try again.