首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

近日学习py代码片段

2012-10-27 
近期学习py代码片段早上刚好看到几个挺不错的帖子关于mixin的http://blog.csdn.net/lanphaday/archive/200

近期学习py代码片段

早上刚好看到几个挺不错的帖子

关于mixin的

http://blog.csdn.net/lanphaday/archive/2007/06/18/1656969.aspx

http://wiki.woodpecker.org.cn/moin/IntroMixin

关于一些文章

http://www.douban.com/group/topic/13716762/

关于decorator

http://taoyh163.blog.163.com/blog/static/19580356200711463029809/

?

刚好这几天在写些玩具代码玩玩,被一个实现卡了好久,顺带翻了不少看了但已经淡忘的知识点。呵呵

1.__metaclass__.可以在类定义后做些约束扩展。

class MetaC(type):      def __init__(cls, name, bases, attrd):          super(MetaC, cls).__init__(name, bases, attrd)          print '*** Created class %r at: %s' % (                 name, ctime())class Foo(object):      __metaclass__ = MetaC      def __init__(self):          print '*** Instantiated class %r at: %s' % (                 self.__class__.__name__, ctime())

?

2.decorator

def arg_sayer(what):        def what_sayer(meth):                def new(self, *args, **kws):                        print what                        return meth(self, *args, **kws)                return new        return what_sayerdef FooMaker(word):        class Foo(object):                @arg_sayer(word)                def say(self):             pass        return Foo()foo1 = FooMaker('this')foo2 = FooMaker('that')print type(foo1),; foo1.say()  # prints: <class '__main__.Foo'> thisprint type(foo2),; foo2.say()  # prints: <class '__main__.Foo'> that

?

3.单例

>>> class Singleton(object):        _instance = None        def __new__(cls, *args, **kwargs):            if not cls._instance:                cls._instance = super(Singleton, cls).__new__(                                   cls, *args, **kwargs)            return cls._instance>>> class C(Singleton):        pass>>> class D(Singleton):        pass>>> c = C()>>> d = C()>>> id(c), id(d)(10049912, 10049912)>>> e = D()>>> f = D()>>> id(e)10113672>>> id(f)10113672>>> g = C()>>> id(g)10049912

?

热点排行