Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Korakot Chaovavanich http://korakot.stumbleupon.com

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Collection of a bunch of named stuff

Taken from this recipe and its comments.
   1  
   2  class bunch(dict):
   3      def __init__(self,**kw):
   4          dict.__init__(self,kw)
   5          self.__dict__.update(kw)

Usage is simple.
   1  
   2  >>> o = bunch(a='A', b='B')
   3  >>> o
   4  {'a': 'A', 'b': 'B'}
   5  >>> o.a
   6  'A'
   7  >>> o.b
   8  'B'
   9  >>> 

You can use it as both an object and dict.

classmethod and staticmethod

   1  
   2  class K(object):
   3  
   4    # normal method (instance method)
   5    def method1(self):
   6      print 'obj.method1() becomes method1(obj)'
   7  
   8    # class method
   9    def method2(cls):
  10      print 'K.method2() becomes method2(K)'
  11    method2 = classmethod(method2)
  12  
  13    # static method
  14    def method3():
  15      print 'K.method3() become just method3()'
  16    method3 = staticmethod(method3)
  17  
  18  obj = K()
  19  obj.method1()
  20  K.method2()
  21  K.method3()

Old and new-style class

Old style class
   1  
   2  class K:
   3    ...

New style class
   1  
   2  class K(object):
   3    ...

Some features such as properties are only avaiable in new-style class.
Learn more about New-style class
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS