這篇文章主要介紹了Python的__builtins__模塊中的一些要點知識,是Python學習中的基礎,需要的朋友可以參考下
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 "<pyshell#55>", line 1, in <module>
- 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)返回的是實例對象專有的屬性、其所屬類的屬性、其所屬類基類繼承來的屬性?!緦︻悓ο蟮娜魏涡薷模貙⒎从车狡鋵嵗龑ο笊?對基類的任何修改,也必將反映到派生類上。當然,屬性遮蔽的情況除外?!?/p>
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
- >>>
新聞熱點
疑難解答