Python Snippets(3)

1.
*attr()

  1. class myClass(object):
  2.     def __init__(self):
  3.         self.foo = 100
  4. myInst = myClass()
  5. print hasattr(myInst, 'foo')
  6. print getattr(myInst, 'foo')
  7. print hasattr(myInst, 'bar')
  8. #print getattr(myInst, 'bar')
  9. print getattr(myInst, 'bar', 'oooops')
  10. setattr(myInst, 'bar', 'my attr')
  11. print getattr(myInst,'bar')
  12. print dir(myInst)
  13. print getattr(myInst,'bar')
  14. delattr(myInst, 'foo')
  15. print dir(myInst)

2.
字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。
decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode(‘gb2312′),表示将gb2312编码的字符串str1转换成unicode编码。
encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode(‘gb2312′),表示将unicode编码的字符串str2转换成gb2312编码。

3.
iter, next

  1. #! /usr/bin/env python
  2.  
  3. from random import choice
  4.  
  5. class RandSeq(object):
  6.     """docstrinRandSeq"""
  7.     def __init__(self, seq):
  8.         self.data = seq
  9.  
  10.     def __iter__(self):
  11.         return self
  12.  
  13.     def next(self):
  14.         return choice(self.data)
  15.  
  16. class AnyIter(object):
  17.     def __init__(self, data, safe = False):
  18.         self.safe = safe
  19.         self.iter = iter(data)
  20.  
  21.     def __iter__(self):
  22.         return self
  23.  
  24.     def next(self, howmany = 1):
  25.         retval = []
  26.         for eachItem in range(howmany):
  27.             try:
  28.                 retval.append(self.iter.next())
  29.             except StopIteration:
  30.                 if self.safe:
  31.                     break
  32.                 else:
  33.                     raise
  34.         return retval
  35.  
  36. if __name__ == '__main__':
  37.     '''
  38.     for eachItem in RandSeq(('Rock', 'Paper', 'Scissors')):
  39.         print eachItem
  40.     '''
  41.     a = AnyIter(range(10))
  42.     i = iter(a)
  43.  
  44.     for j in range(1,5):
  45.         print j,' : ', i.next(j)

4.

  1. a.__dict__['x'], then type(a).__dict__['x']

5.

  1. def __getattribute__(self, key):
  2.     "Emulate type_getattro() in Objects/typeobject.c"
  3.     v = object.__getattribute__(self, key)
  4.     if hasattr(v, '__get__'):
  5.        return v.__get__(None, self)
  6.     return v
  7. '''
  8. The important points to remember are:
  9.  
  10. descriptors are invoked by the __getattribute__() method
  11. overriding __getattribute__() prevents automatic descriptor calls
  12. __getattribute__() is only available with new style classes and objects
  13. object.__getattribute__() and type.__getattribute__() make different calls to __get__().
  14. data descriptors always override instance dictionaries.
  15. non-data descriptors may be overridden by instance dictionaries.
  16. '''

6.

  1. x.foo
  2. '''
  3. type(x).__dict__['foo'].__get__(x, type(x))
  4. '''

7.

  1. class Property(object):
  2.     "Emulate PyProperty_Type() in Objects/descrobject.c"
  3.  
  4.     def __init__(self, fget=None, fset=None, fdel=None, doc=None):
  5.         self.fget = fget
  6.         self.fset = fset
  7.         self.fdel = fdel
  8.         if doc is None and fget is not None:
  9.             doc = fget.__doc__
  10.         self.__doc__ = doc
  11.  
  12.     def __get__(self, obj, objtype=None):
  13.         if obj is None:
  14.             return self
  15.         if self.fget is None:
  16.             raise AttributeError("unreadable attribute")
  17.         return self.fget(obj)
  18.  
  19.     def __set__(self, obj, value):
  20.         if self.fset is None:
  21.             raise AttributeError("can't set attribute")
  22.         self.fset(obj, value)
  23.  
  24.     def __delete__(self, obj):
  25.         if self.fdel is None:
  26.             raise AttributeError("can't delete attribute")
  27.         self.fdel(obj)
  28.  
  29.     def getter(self, fget):
  30.         return type(self)(fget, self.fset, self.fdel, self.__doc__)
  31.  
  32.     def setter(self, fset):
  33.         return type(self)(self.fget, fset, self.fdel, self.__doc__)
  34.  
  35.     def deleter(self, fdel):
  36.         return type(self)(self.fget, self.fset, fdel, self.__doc__)

发布者

690130229

coder,喜欢安静,喜欢读书,wechat: leslie-liya

发表评论