美文网首页
python内置函数(4)

python内置函数(4)

作者: 以后的以后_hzh | 来源:发表于2017-11-04 18:03 被阅读0次

31.

bytearray()方法返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。

实例:

>>> bytearray()

bytearray(b'')

>>> bytearray([1,2,3])

bytearray(b'\x01\x02\x03')

>>> bytearray('runoob','utf-8')

bytearray(b'runoob')

32.

filter()函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

实例:

>>> def odd(n):

...    return n % 2 ==1

...

>>> list=filter(odd,[1,2,3,4,5,6,7,8,11,45])

>>> next(list)

1

>>> next(list)

3

>>> next(list)

5

>>> next(list)

7

>>> next(list)

11

>>> next(list)

45

33.issubclass()方法用于判断参数 class 是否是类型参数 classinfo 的子类。

实例:

>>> class A:

...    pass

...

>>> class B(A):

...    pass

...

>>> print(issubclass(B,A))

True

34.pow()方法返回 xy(x的y次方) 的值。

实例:

>>> import math

>>> print("math.pow(100,2):",math.pow(100,2))

math.pow(100,2): 10000.0

>>> print("pow(100,2):",pow(100,2))

pow(100,2): 10000

>>> print("math.pow(100,-2):",math.pow(100,-2))

math.pow(100,-2): 0.0001

>>> print("math.pow(2,4):",math.pow(2,4))

math.pow(2,4): 16.0

>>> print("math.pow(2,0):",math.pow(2,0))

math.pow(2,0): 1.0

35.super()函数用于调用下一个父类(超类)并返回该父类实例的方法。

super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。

MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。

实例:

>>> class FooParent(object):

...    def __init__(self):

...            self.parent='I am the parent.'

...            print('Parent')

...    def bar(self,message):

...            print("%s from Parent" % message)

...

>>> class FooChild(FooParent):

...    def __init__(self):

...            super(FooChild,self).__init__()

...            print('Child')

...    def bar(self,message):

...            super(FooChild,self).bar(message)

...            print('Child bar fuction')

...            print(self.parent)

...

>>> if __name__=="__main__":

...    foochild=FooChild()

...    foochild.bar("HelloWorld")

...

Parent

Child

HelloWorld from Parent

Child bar fuction

I am the parent.

36.bytes 函数返回一个新的 bytes 对象,该对象是一个 0 <= x < 256 区间内的整数不可变序列。它是 bytearray 的不可变版本。

实例:

>>> a=bytes([1,2,3,4])

>>> a

b'\x01\x02\x03\x04'

>>> type(a)

>>> a=bytes("hello","ascii")

>>> a

b'hello'

>>> type(a)

<class 'bytes'>

37.float()函数用于将整数和字符串转换成浮点数。

>>> float(1)

1.0

>>> float(111)

111.0

>>> float(-111)

-111.0

>>> float(-111.33)

-111.33

>>> float('-66.66')

-66.66

38.iter()函数用来生成迭代器。

实例:

>>> lst=[1,2,3]

>>> for i in iter(lst):

...    print(i)

...

1

2

3

39.print()方法用于打印输出,最常见的一个函数。

>>> print(1)

1

>>> print("hello python")

hello python

>>> a=1

>>> b='asa'

>>> print(a,b)

1 asa

40.tuple 函数将列表转换为元组。

>>> list=['baidu','taobao','tengxun']

>>> tuple=tuple(list)

>>> tuple

('baidu', 'taobao', 'tengxun')

相关文章

网友评论

      本文标题:python内置函数(4)

      本文链接:https://www.haomeiwen.com/subject/thofmxtx.html