1.isinstance函數:除了以一個類型作為參數,還可以以一個類型元組作為參數。
isinstance(obj,basestring)===isinstance(obj,(str,unicode))
2.getattr函數:可以給一個默認值,以免觸發錯誤。
writte=getattr(obj,'write',sys.stdout.write)
3.type函數:即可以得到一個對象的類型,也可以直接由它創建一個新類型:
>>> Point=type('Point',(object,),{'x':0,'y':0}) >>> p=Point() >>> p.x,p.y (0, 0) >>> p=Point(3,8) Traceback (most recent call last): File "", line 1, in p=Point(3,8) TypeError: object() takes no parameters >>> pprint.pprint(dir(Point)) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'x', 'y'] >>> p.name='source point' >>> p.name 'source point' >>> pprint.pprint(dir(p)) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'x', 'y'] >>> def tostr(self): return '(%s,%s)'%(self.x,self.y) >>> Point.__str__=tostr >>> print p (0,0) >>> def init(self,x,y): self.x,self.y=x,y >>> Point.__init__=init >>> p2=Point(6,8) >>> print p2 (6,8) >>>
4.issubclass(bool,int)==True
5.numbers.Number是所有數字類型的基類
6.type(None)==NoneType,None是一個常量
7.iter函數除了iter(object)形式,還有iter(callable,sentinel)也是返回一個iterator對象
>>> def getrand(): import random return random.randint(1,100) >>> for i in iter(getrand,50):print i,#獲取第一次得到50之前的所有1-100的隨機數 32 19 82 28 30 41 100 39 71 29 45 30 94 77 62 26 25 19 82 20 55 20 43 73 >>> for i in iter(getrand,50):print i,#獲取第一次得到50之前的所有1-100的隨機數 22 54 14 25 60 65 16 80 61 5 48 61 2 30 90 98 70 10 55 45 23 72 87 39 70 3 84 85 >>>
8.BaseException是一切exceptions的基類,Exception只是一切不exit的exceptions的基類
9.locals/globals/vars/dir:
[1]locals/globals很簡單,是相對于當前作用域的本地/全局對象dict;
[2]vars()==locals(),vars(obj)==obj.__dict__
[3]沒有參數,set(dir())==set(locals().keys());if hasattr(obj,'__dir__')=>dir(obj)==obj.__dir__();否則,如果obj是模塊對象,dir(obj)返回的是模塊的所有屬性;如果obj是類對象,dir(obj)返回的是類的所有屬性,然后是從基類繼承來的屬性;如果obj是實例對象,dir(obj)返回的是實例對象專有的屬性、其所屬類的屬性、其所屬類基類繼承來的屬性。【對類對象的任何修改,必將反映到其實例對象上;對基類的任何修改,也必將反映到派生類上。當然,屬性遮蔽的情況除外。】
10.enumerate函數:enumerate(obj,[start]),如果定義了start,則序數將從start開始,而不是從默認的零開始。
>>> for i,name in enumerate(['C','C++','CSharp','Java','Python'],1): print '%d.%s'%(i,name) 1.C 2.C++ 3.CSharp 4.Java 5.Python >>>
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
