当前位置:天才代写 > tutorial > Python教程 > Python __builtins__模块拾穗

Python __builtins__模块拾穗

2017-11-02 08:00 星期四 所属: Python教程 浏览:456

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)返回的是实例工具专有的属性、其所属类的属性、其所属类基类担任来的属性。【对类工具的任何修改,必将反应到其实例工具上;对基类的任何修改,也必将反应到派生类上。虽然,属性遮蔽的环境除外。】

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
>>>

 

    关键字:

天才代写-代写联系方式