Python内建函数(C)

来源:互联网 发布:淘宝封店重开技术 编辑:程序博客网 时间:2024/06/05 19:39

说明:检查对象object是否可调用。如果返回True,object任然可能调用失败,但如果返回False,调用对象ojbect绝对不会成功。注意:类是可调用的,而类的实例实现了__call__()方法才可调用。

示例:

复制代码
>>> callable(0)False>>> callable("mystring")False>>> def add(a, b):…     return a + b…>>> callable(add)True>>> class A:…      def method(self):…         return 0…>>> callable(A)True>>> a = A()>>> callable(a)False>>> class B:…     def __call__(self):…         return 0…>>> callable(B)True>>> b = B()>>> callable(b)True
复制代码

 

  •  chr(i)

说明:返回整数i对应的ASCII字符。与ord()作用相反。

参数x:取值范围[0, 255]之间的正数。

示例:

>>> chr(97)'a'>>> ord('a')97

 

  • classmethod()

说明:classmethod是用来指定一个类的方法为类方法,没有此参数指定的类的方法为实例方法,使用方法如下:

class C:    @classmethod    def f(cls, arg1, arg2, ...): ...

类方法既可以直接类调用(C.f()),也可以进行实例调用(C().f())。

示例:

复制代码
>>> class C:...     @classmethod...     def f(self):...             print "This is a class method"...>>> C.f()This is a class method>>> c = C()>>> c.f()This is a class method>>> class D:...     def f(self):...             print " This is not a class method "...>>> D.f()Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: unbound method f() must be called with D instance as first argument (got nothing instead)>>> d = D()>>> d.f()This is not a class method
复制代码

 

  • cmp(x, y)

说明:比较两个对象x和y,如果x < y ,返回负数;x == y, 返回0;x > y,返回正数。

示例:

复制代码
>>> cmp(1, 2)-1>>> cmp(3, 3)0>>> cmp(4, 3)1>>> cmp('abc','a')1
复制代码

 

  • compile(source, filename, mode[, flags[, dont_inherit]])

说明:将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。

参数source:字符串或者AST(Abstract Syntax Trees)对象。

参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。

参数model:指定编译代码的种类。可以指定为 ‘exec’,’eval’,’single’。

参数flag和dont_inherit:这两个参数暂不介绍,碰到时再具体介绍。

示例:

复制代码
>>> code = "for i in range(0, 10): print i">>> cmpcode = compile(code, '', 'exec')>>> exec cmpcode0123456789>>> str = "3 * 4 + 5">>> a = compile(str,'','eval')>>> eval(a)17
复制代码

 

  • complex([real[, imag]])

说明:创建一个值为real + imag * j的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。

参数real: int, long, float或字符串;

参数imag: int, long, float。

示例:

复制代码
>>> complex(3, 4)(3 + 4j)>>> complex(3)(3 + 0j)>>> complex("3")(3 + 0j)>>> complex("3 + 4j")(3 + 4j)
复制代码
原创粉丝点击