Python內置函數彙總

Talk is cheap, show me the code. 

if __name__ == '__main__':
    """abs() 取絕對值"""
    assert abs(-1) == 1

    """all(iterator) 迭代對象中 全部爲True 才返回True"""
    assert all([0, '', None, False]) is False
    assert all([]) is True
    assert all(()) is True

    """any(iterator) 迭代對象中 有一個元素爲True 就返回True"""
    assert any([0, '', None, False, True]) is True
    assert any([]) is False
    assert any(()) is False

    """basestring() 方法是 str 和 unicode 的超類(父類)"""
    assert isinstance('Hello', (str, unicode))
    assert isinstance('Hello', basestring)

    """bin()返回一個整數int或者長整數long int 的二進制表示"""
    assert bin(10) == '0b1010'
    assert isinstance(bin(20), basestring)

    """將給定參數轉換爲bool類型"""
    assert not bool()
    assert not bool(0)
    assert bool(1)
    assert issubclass(bool, int)  # bool 是int的子類

    """bytearray() 返回一個新的字節數組"""
    assert bytearray() == bytearray(b'')
    assert bytearray([1, 2, 3]) == bytearray(b'\x01\x02\x03')
    assert bytearray('hello', 'utf-8') == bytearray(b'hello')

    """callable() 檢查函數是否是可調用的"""
    assert not callable(0)
    assert not callable('string')

    """chr() 返回整數對應的ASCII字符"""
    assert chr(0x61) == 'a'
    assert chr(97) == 'a'

    """classmethod 裝飾類函數不需要實例化"""
    pass

    """cmp(x, y) 比較兩個對象"""
    assert cmp(80, 100) == -1
    assert not cmp(80, 80)
    assert cmp(100, 80) == 1

    """compile() 將一個字符串編譯爲字節代碼"""

    """complex() 創建一個複數"""

    """delattr() 刪除屬性"""
    # delattr(object, name)

    """dict() 創建一個字典"""
    assert dict(a='a', b='b', c='c') == {'a': 'a', 'b': 'b', 'c': 'c'}
    assert dict(zip(['a', 'b', 'c'], [1, 2, 3])) == {'a': 1, 'b': 2, 'c': 3}
    assert dict([('a', 1), ('b', 2), ('c', 3)]) == {'a': 1, 'b': 2, 'c': 3}

    """dir() """
    print dir()  # 獲得當前模塊的屬性列表
    print dir([])  # 查看列表的方法

    """divmod() 返回商和餘數的元組(a//b, a%b)"""
    assert divmod(7, 2) == (3, 1)
    assert divmod(1 + 2j, 1 + 0.5j) == ((1+0j), 1.5j)

    """enumerate() 將一個可遍歷的數據對象 組合成 一個索引樹"""
    # start: 下標起始位置
    assert list(enumerate(['Spring', 'Summer', 'Fall', 'Winter'], start=1)) == [(1, 'Spring'), (2, 'Summer'),
                                                                                (3, 'Fall'), (4, 'Winter')]

    """eval() 執行一個字符串表達式,並返回表達式的值"""
    n = 81
    assert eval('n + 1') == 82

    """execfile() 用來執行一個文件"""

    """file() 別名 open() 返回一個文件對象"""

    """filter(func, iterable) 返回符合過濾函數的新列表 """
    assert filter(lambda x: x % 2 == 1, range(1, 10)) == [1, 3, 5, 7, 9]

    """float() 將整數或字符串轉換成浮點數"""
    assert float('123') == 123.0

    """format 格式化函數"""
    assert "{1} {0} {1}".format("hello", "world") == 'world hello world'
    assert "{:.2f}".format(3.1415926) == '3.14'

    """frozenset() 返回一個凍結(不能再添加和刪除任何元素)的集合"""
    frozenset(range(10))

    """getattr() 返回一個對象的屬性值"""
    getattr('obj', 'field', 'default')

    """globals() 以字典的形式返回當前位置的全部局部變量"""
    print globals()

    """hasattr() 判斷對象是否包含對應的屬性"""
    hasattr(object, 'field_name')

    """hash() 獲取一個對象的哈希值"""
    assert -1267296259 == hash('hello')

    """help() 查看函數或模塊用途的詳細說明"""

    """hex() 將10進制整數轉換成16進制,以字符串形式表示"""
    assert hex(255) == '0xff'
    assert issubclass(type(hex(255)), str)

    """id() 返回對象的唯一標識符, CPython 中id()函數用於獲取對象的內存地址"""
    print id('hello')

    """input() raw_input() 獲取控制檯的輸入"""
    # input('receive int:')
    # raw_input('all string:')  # 任何類型都以字符串接收

    """int() 將一個字符串或數字轉換爲整數"""
    assert int() == 0
    assert int('10', 16) == 16

    """isinstance() 判斷一個對象是否是一個已知的類型,且支持繼承關係,type()不考慮繼承關係"""
    assert isinstance(2, int)
    assert isinstance(2, (str, int, list))

    """issubclass(class, classinfo) 判斷參數class是否是classinfo的子類"""
    class A:
        pass
    class B(A):
        pass
    assert issubclass(B, A)

    """iter() 生成迭代器"""
    for i in iter(range(5)):
        print i

    """len() 返回對象(字符、列表、元組等)長度或項目個數"""
    assert len('hello') == 5

    """list(tuple) 將元組轉換爲列表"""
    assert isinstance(list((1, 2, 3)), list)

    """locals() 以字典類型返回當前位置的全部局部變量"""
    def func_c(args):
        field = 1
        print locals()
    func_c('arg')  # {'field': 1, 'args': 'arg'}

    """long() 將數字或字符串轉換成一個長整型"""
    assert long('123') == 123L

    """map(function, iterable, ...) 根據提供的函數對指定序列做映射"""
    assert map(lambda x, y: x+y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) == [3, 7, 11, 15, 19]

    """max(x, y, z, ...) 返回給定參數的最大值"""
    assert max(-20, 0, 30) == 30
    assert max('1,2,3,4') == '4'

    """min(x, y, z, ...) 返回指定參數的最小值"""

    """memoryview(obj) 返回給定參數的內存查看對象"""
    view = memoryview('abcdef')
    assert view[-1] == 'f'
    print view[1:4]  # <memory at 0x02715760>
    assert view[1:3].tobytes() == 'bc'

    """next(iterator[, default]) 返回迭代器的下一個項目"""
    # 首先獲得Iterator對象:
    it = iter([1, 2, 3, 4, 5])
    while True:
        try:
            # 獲得下一個值:
            x = next(it)
            print(x)
        except StopIteration:
            # 沒有下一個元素則會觸發 StopIteration 異常
            break

    """oct() 將一個整數轉換成8進制字符串"""
    assert '012' == oct(10)

    """open(name[, mode[, buffering]]) 打開一個文件,創建file對象"""

    """ord(char) 返回字符對應的ASCII數值"""
    assert ord('a') == 97

    """property() 在新式類中返回屬性值"""
    class C(object):
        def __init__(self):
            self._x = None
        @property
        def x(self):
            """I'm the 'x' property."""
            return self._x
        @x.setter
        def x(self, value):
            self._x = value
        @x.deleter
        def x(self):
            del self._x

    """range(start, stop[, step]) 創建並返回一個整數列表"""

    """raw_input() 獲取控制檯的輸入,返回結果都是字符串類型"""

    """reduce(function, iterable[, initializer]) 對參數序列中元素進行累積"""
    assert reduce(lambda a, b: a + b, range(0, 5)) == 10

    """reload(module) 重載之前載入的模塊"""

    """repr(object) 將對象轉化爲供解釋器讀取的形式"""
    str_obj = 'hello'
    repr(str_obj)

    """reverse() 反轉列表中的元素"""
    list_obj = [1, 2, 'a', 3.0, 0x55, 012]
    list_obj.reverse()
    assert [10, 85, 3.0, 'a', 2, 1] == list_obj

    """round(x[, n]) 返回浮點數x的四捨五入值(會受到計算機精度的影響)"""
    assert round(3.1415926, 4) == 3.1416

    """set([iterable]) 創建一個無序不重複元素集"""
    s1 = set('hello')
    s2 = set('world')
    assert s1 == {'h', 'e', 'l', 'o'}
    print s1 & s2  # 交集 set(['l', 'o'])
    print s1 | s2  # 並集 set(['e', 'd', 'h', 'l', 'o', 'r', 'w'])
    print s1 ^ s2  # 異或 set(['e', 'd', 'h', 'r', 'w'])
    print s1 - s2  # 差集 set(['h', 'e'])

    """setattr(object, name, value) 爲對象設置屬性值"""

    """slice(start, stop[, step]) 返回一個切片對象"""
    assert range(10)[slice(2, 6)] == [2, 3, 4, 5]

    """sorted(iterable, cmp=None, key=None, reverse=False) 對所有可迭代對象進行排序操作"""

    """staticmethod() 返回函數的靜態方法"""

    """str() 將對象轉化爲適於人閱讀的形式"""

    """"sum(iterable[, extra]) 求和計算"""
    assert sum((2, 3, 4), 1) == 10

    """super() 調用父類(超類)的一個方法"""
    class FooParent(object):
        def __init__(self):
            self.parent = 'I\'m the parent.'
            print ('Parent')
        def bar(self, message):
            print ("%s from Parent" % message)
    class FooChild(FooParent):
        def __init__(self):
            # super(FooChild,self) 首先找到 FooChild 的父類(就是類 FooParent),然後把類 FooChild 的對象轉換爲類 FooParent 的對象
            super(FooChild, self).__init__()
            print ('Child')
        def bar(self, message):
            super(FooChild, self).bar(message)
            print ('Child bar fuction')
            print (self.parent)

    """tuple(iterable) 將列表轉換爲元組"""
    assert tuple({'a': 1, 'b': 2}) == ('a', 'b')

    """type(name, bases, dict) 一個參數返回對象類型, 三個參數,返回新的類型對象。"""
    assert type('str') == str
    class X(object):
        a = 1
    obj = type('X', (object,), dict(a=1))
    print obj  # <class '__main__.X'>

    """unichr() 返回unicode的字符"""
    assert unichr(97) == u'a'

    """vars([object]) 返回對象object的屬性和屬性值的字典對象"""
    class Y(object):
        b = 2
    print(vars(Y))  # {'__dict__': <attribute '__dict__' of 'Y' objects>, '__module__': '__main__', 'b': 2, '__weakref__': <attribute '__weakref__' of 'Y' objects>, '__doc__': None}

    """xrange() 與range不同的是生成的不是一個數組,而是一個生成器"""
    xrange1 = xrange(3, 5)
    assert list(xrange1) == [3, 4]

    """zip([iterable, ...]) 將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表"""
    nums = ['flower', 'flow', 'flight']
    for i in zip(*nums):
        print(i)
    # ('f', 'f', 'f')
    # ('l', 'l', 'l')
    # ('o', 'o', 'i')
    # ('w', 'w', 'g')

    """__import__() 動態加載類和函數"""
    # 如果一個模塊經常變化就可以使用 __import__() 來動態載入

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章