python内置方法、模块讲解(四)

  • 2016-02-24 00:08:18
  • 1312
  • 0

十二、chr方法

1、定义:

chr(...)
    chr(i) -> character

    Return a string of one character with ordinal i; 0 <= i < 256.

2、解释:将一个整型转换成字符即将ASCII码转换成字符

3、举例:

>>> chr(97)
'a'
>>> chr(107)
'k'
>>> chr(50)
'2'

十三、classmethod类

​​​1、定义:

class classmethod(object)
 |  classmethod(function) -> method
 |
 |  Convert a function to be a class method.
 |
 |  A class method receives the class as implicit first argument,
 |  just like an instance method receives the instance.
 |  To declare a class method, use this idiom:
 |
 |    class C:
 |        def f(cls, arg1, arg2, ...): ...
 |        f = classmethod(f)
 |
 |  It can be called either on the class (e.g. C.f()) or on an instance
 |  (e.g. C().f()).  The instance is ignored except for its class.
 |  If a class method is called for a derived class, the derived class
 |  object is passed as the implied first argument.

2、解释:​​将一个函数转变成类方法,类方法与实例方法相似,是把类当作第一个默认参数。 类方法可以类或者实例调用, 其中实例的调用的时候,实例本身是被忽略的。如果一个类方法被一个子(继承)类调用,那么这个子类会被当作第一个默认参数。

​3、举例:

class C:
    def f(cls):
        pass
    f = classmethod(f)
    @classmethod
    def f(cls):
        pass
以上两种方式都可以定义类方法f()

​十四、cmp方法

​1、定义:

cmp(...)
    cmp(x, y) -> integer

    Return negative if x<y, zero if x==y, positive if x>y.

​2、解释:用于比对两个参数, 如果x<y 返回负-1, 如果x==y 返回0,如果x>y返回1

​3、举例:

>>> cmp('4','2')
1
>>> cmp(6,0)
1
>>> cmp(6,6)
0
>>> cmp(6,9)
-1

​十五、coerce方法

​1、定义:

coerce(...)
    coerce(x, y) -> (x1, y1)

    Return a tuple consisting of the two numeric arguments converted to
    a common type, using the same rules as used by arithmetic operations.
    If coercion is not possible, raise TypeError.

​2、解释:通过使用相同的规则,返回两个相同常用类型的数字参数, 如果转换不可能,则抛出TypeError错误类型

3、举例:

 

>>> coerce(1,2)
(1, 2)
>>> coerce(1L,2)
(1L, 2L)
>>> coerce(1,2L)
(1L, 2L)
>>> coerce(1.0,2L)
(1.0, 2.0)
>>> coerce(1.0,2L)
注:复数也会做相同转换


发表评论

* *