Python 内置函数详解1

内置函数

abs 函数

功能: 返回数字的绝对值

abs(x)

x 表示为表达式, 可以是 -10-5 这样的形式

返回值: 正数是本身,负数是相反数

all 函数

功能: 判断可迭代参数 iterable 中所有的元素是否为 True

返回值: 如果是返回 True,只要有一个 False,则返回 False (元素除了是 0、空、None、False 外都算 True)

语法: all(iterable) 参数可以是元组或者列表

实现:

def my_all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

实例

all(['a', 'b', 'c', 'd'])  # 列表 list,元素都不为空或0     True
all(['a', 'b', '', 'd'])  # 列表list,存在一个为空的元素    False
all([0, 1,2, 3])  # 列表list,存在一个为0的元素            False
all(('a', 'b', 'c', 'd'))  # 元组tuple,元素都不为空或0    True
all(('a', 'b', '', 'd'))  # 元组tuple,存在一个为空的元素   False
all((0, 1, 2, 3))  # 元组tuple,存在一个为0的元素           False
all([])  # 空列表       True
all(())  # 空元组       True

any 函数

功能: 用于判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True (元素除了是 0、空、False 外都算 True)

函数等价于

def my_any(iterable):
    for element in iterable:
        if element:
            return True
    return False

参数类型: 和 all 是一样的, 只接受元组和列表

basestring 函数

basestring() 方法是 str 和 unicode 的超类(父类),也是抽象类,因此不能被调用和实例化,但可以被用来判断一个对象是否为 str 或者 unicode 的实例,isinstance(obj, basestring) 等价于 isinstance(obj, (str, unicode))

不过Python 3 不支持这个函数,改为 str() 函数

参数:无

返回值:无

实例: 如果 Hello world 是 字符串则返回 True,判断字符串的内置函数可以是 str 或者 basestring , 当然建议选择 str ,因为 Python 不支持 basestring

print(isinstance("Hello world", str))
print(isinstance("Hello world", basestring))

bin 函数

返回值: 返回一个字符串(参数的二进制表示)

语法: bin(x) 参数 x 可以是 int 或者 long int 数字

print(bin(100))
# 0b1100100

0b 表示这个数字是二进制的提示

bool 函数

功能: 用于将给定参数转换为布尔类型,如果没有参数,返回 False

bool 是 int 的子类

语法:

class bool([x])

案例:

s1 = bool((0,0,0,False)) # True
s2 = bool([0,False])     # True
s3 = bool("hello")       # True
s4 = bool([1,1,1])       # True

s5 = bool(False)         # False
s6 = bool()              # False
s7 = bool({})            # False
s8 = bool([])            # False
s9 = bool('')            # False
s10 = bool(0)            # False
s11 = bool(())			 # False

bytearray 函数

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

语法:

class bytearray([source[, encoding[, errors]]])

参数:

  1. 如果 source 为整数,则返回一个长度为 source 的初始化数组;
  2. 如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列;
  3. 如果 source 为可迭代类型,则元素必须为[0 ,255] 中的整数;
  4. 如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray
  5. 如果没有输入任何参数,默认就是初始化数组为0个元素.

实例:

list1 = bytearray()         # 无参数
print(list1)                # bytearray(b'')
print(list(list1))          # []

list2 = bytearray([1,2,3])  # 可迭代类型
print(list2)                # bytearray(b'\x01\x02\x03')
print(list(list2))          # [1,2,3]

list3 = bytearray('runoob', 'utf-8')#字符串,按照utf-8转换为字节序列
print(list3)                # bytearray(b'runoob')
print(list(list3))          # [114,117,110,111,111,98]

list4 = bytearray(3)        # 整数
print(list4)                # bytearray(b'\x00\x00\x00')
print(list(list4))          # [0,0,0]

callable 函数

功能:用于检查一个对象是否是可调用的。如果返回 True,object 仍然可能调用失败;但如果返回 False,调用对象 object 绝对不会成功。

对于函数、方法、lambda 函式、 类以及实现了 __call__ 方法的类实例, 它都返回 True

语法: callable(object)

参数: object 对象

返回值:可调用返回 True,否则返回 False

实例

# 第一种可调用的情况
def add(a,b):
    return a+b
callable(add) #True

# 第二种可调用的情况
class A:
    def mode(self):
        return 0
callable(A) #True

# 不可调用的情况,实例没有 __call__的类实例
a = A()
callable(a)  # 没有实现 __call__, 返回 False

# 可调用的类实例,因为实现了 __call__
class B:
    def __call__(self):
        return 0
b = B()
callable(b)               # 实现 __call__, 返回 True

__call__ 的解释:该方法的功能类似于在类中重载 () 运算符,使得类实例对象可以像调用普通函数那样,以“对象名()”的形式使用

# 使用案例1
class CLanguage:
    # 定义__call__方法
    def __call__(self,name,add):
        print("调用__call__()方法",name,add)

clangs = CLanguage()
# 下面这两行等价
clangs("python","内置方法")
clangs.__call__("python","内置方法")

# 使用案例2
def say():
    print("你说了什么?")
say()
say.__call__()

# 使用案例3:  __call__() 弥补 hasattr() 函数的短板

hasattr 函数

功能:用于判断对象是否包含对应的属性。

语法: hasattr(object, name)
object – 对象
name – 字符串,属性名

返回值:如果对象有该属性返回 True,否则返回 False

实例

class Coordinate:
    x = 10
    y = -5
    z = 0
    def move(self):
        pass

point1 = Coordinate()
print(hasattr(point1, 'x')) #True
print(hasattr(point1, 'y')) #True
print(hasattr(point1, 'z')) #True
print(hasattr(point1,'move')) #True
print(hasattr(point1, 'no'))  # 没有该属性,返回 False

缺陷:它无法判断该指定的名称,到底是类属性还是类方法

解决办法:利用 __call__

class CLanguage:
    def __init__ (self):
        self.name = "python语言"
        self.add = "怎么学?"
    def say(self):
        print("学Python")

clangs = CLanguage()
if hasattr(clangs,"say"):
    print(hasattr(clangs.say,"__call__")) #方法也是属于可调用对象
if hasattr(clangs,"name"):
    print(hasattr(clangs.name,"__call__")) # 但是属性却不可调用

追加解释:可以看到,由于 name 是类属性,它没有以 __call__ 为名的 __call__() 方法;而 say 是类方法,它是可调用对象,因此它有 __call__() 方法

chr 函数

功能:用一个范围在 range(256)内的(就是0~255)整数作参数,返回一个对应的字符

语法 chr(i) i 可以是10进制也可以是16进制的形式的数字

返回值:返回值是当前整数对应的 ASCII 字符

实例

print(chr(0x30), chr(0x31), chr(0x61))      # 十六进制  0 1 a
print(chr(48), chr(49), chr(97))            # 十进制  0 1 a

classmethod 修饰符

描述:classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等

参数:无

返回值:返回函数的类方法

实例

class A(object):
    bar = 1
    def func1(self):
        print('foo')
    @classmethod
    def func2(cls):
        print('func2')
        print(cls.bar) # 1
        cls().func1()  # 调用 foo 方法
A.func2()  # 不需要实例化

cmp 函数

功能:cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1

语法:以下是 cmp() 方法的语法:
cmp( x, y ) x ,y 为数值表达式

只不过在 python 3 已经去掉这个函数了,被operator 替换

import operator
print(operator.eq(80, 100)) # ==
print(operator.ne(80,100))  # !=
print(operator.lt(80,100))  # <
print(operator.le(80,100))  # <=
print(operator.gt(80,100))  # >
print(operator.ge(80,100))  # >=

compile 函数

功能:compile() 函数将一个字符串编译为字节代码

语法 compile(source, filename, mode[, flags[, dont_inherit]])

参数:

  • source :字符串或者AST(Abstract Syntax Trees)对象
  • filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值
  • mode :指定编译代码的种类。可以指定为 exec, eval, single
  • flags: 变量作用域,局部命名空间,如果被提供,可以是任何映射对象
  • flags 和 dont_inherit:是用来控制编译源码时的标志

返回值:返回表达式执行结果

案例1:

str = "for i in range(0,10): print(i)"
c = compile(str,'','exec')   # 编译为字节代码对象
print(c)  #<code object <module> at 0x00000208B0AD95D0, file "", line 1>
exec(c)
'''
0
1
2
3
4
5
6
7
8
9
'''

案例2:

str = "a = 3 * 4 + 5  \nprint(a)"
a = compile(str,'','exec')
exec (a) # 17

complex 函数

功能:用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。

如果第一个参数为字符串,则不需要指定第二个参数

语法:class complex([real[, imag]])
参数说明:

  • real – int, long, float或字符串;
  • imag – int, long, float;

返回值:返回一个复数

案例

c1 = complex(1, 2)  # (1 + 2j)
c2 = complex(1)  # 数字 (1 + 0j)
c3 = complex("1")  # 当做字符串处理  (1 + 0j)
# 注意:这个地方在"+"号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错
c4 = complex("1+2j")
print(c1,c2,c3,c4)  #(1+2j) (1+0j) (1+0j) (1+2j)

delattr 函数

功能:delattr 函数用于删除属性

delattr(x, ‘foobar’) 相等于 del x.foobar

语法: delattr(object, name)
object – 对象
name – 必须是对象的属性

返回值:无

class Coordinate:
    x = 10
    y = -5
    z = 0


point1 = Coordinate()
print('x = ', point1.x)
print('y = ', point1.y)
print('z = ', point1.z)

delattr(Coordinate, 'z')
print('--删除 z 属性后--')
print('x = ', point1.x)
print('y = ', point1.y)
# 触发错误
print('z = ', point1.z)

dict 函数

功能:用于创建一个字典

语法:
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

参数:

**kwargs - - - - - -关键字
mapping - - - - - - 元素的容器
iterable - - - - - - - 可迭代对象

返回值:返回一个字典

实例:创建字典的六种方式

#方式 1:
dict1 = {}
dict1['firstname'] = 'ma'
dict1['lastname'] = 'yun'

#方式 2:
dict2 = {'firstname':'ma', 'lastname':'yun'}

#方式 3:
dict3 = dict(firstname = 'ma', lastname = 'yun')

#方式 4:
dict4 = dict([('firstname','ma'), ('lastname', 'yun')])

#方式 5:
dict5 = dict((['firstname','ma'], ['lastname', 'yun']))

#方式6:
dict6 = dict(zip(['firstname', 'lastname'], ['ma', 'yun']))

dir 函数

功能

  • 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;
  • 带参数时,返回参数的属性、方法列表
  • 如果参数包含方法__dir__(),该方法将被调用
  • 如果参数不包含__dir__(),该方法将最大限度地收集参数信息

语法: dir([object]) object – 对象、变量、类型

返回值:返回模块的属性列表

d1 = dir()  # 获得当前模块的属性列表
print(d1)
'''
['__annotations__', '__builtins__', '__cached__', '__doc__', 
'__file__', '__loader__', '__name__', '__package__', '__spec__']
'''

d2 = dir([ ])    # 查看列表的方法
print(d2)
'''
['__add__', '__class__', '__contains__', '__delattr__', 
'__delitem__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__','__getitem__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__','__init_subclass__', '__iter__',
'__le__', '__len__', '__lt__', '__mul__','__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__reversed__',
'__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__',
'__subclasshook__','append', 'clear', 'copy', 'count', 'extend',
'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
'''

divmod 函数

功能:divmod() 函数把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)

在 python 2.3 版本之前不允许处理复数

语法: divmod(a, b)
a: 数字
b: 数字

实例

d1 = divmod(7, 2)  #(3, 1)
print(d1)

d2 = divmod(8, 2)  #(4, 0)
print(d2)

d3 = divmod(1+2j,1+0.5j)  #((1+0j), 1.5j)
print(d3)

enumerate 函数

功能:用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中

Python 2.3. 以上版本可用,2.6 添加 start 参数

语法 :enumerate(sequence, [start=0])
sequence – 一个序列、迭代器或其他支持迭代对象
start – 下标起始位置

返回值:返回 enumerate(枚举) 对象

案例1:

seasons = ['Spring', 'Summer', 'Fall', 'Winter']

l1 = list(enumerate(seasons))
print(l1)#[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

l2 = list(enumerate(seasons, start=1))#下标从 1 开始
print(l2) # [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

案例2:

i = 0
seq = ['one', 'two', 'three']
for element in seq:
    print(i, seq[i])
    i +=1
    
'''
0 one
1 two
2 three
'''

#for 循环使用 enumerate
seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
    print(i, element)
'''
0 one
1 two
2 three
'''

案例三

list1 = ['01','02','03']
dest = ['101','102','103']
unit_element = '1'
'''方法一
for i,element in enumerate(list1):
  list1[i] = unit_element + element
print(list1) #['101', '102', '103']
'''

'''方法二
for i in range(0,len(list1)):
    list1[i] = unit_element+list1[i]
print(list1)
'''

'''方法三
list1 = ["1" + str for str in list1]
print(list1)
'''

eval 函数

功能:用来执行一个字符串表达式,并返回表达式的值

语法:eval(expression[, globals[, locals]])

expression - - 表达式
globals - - 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象
locals - - 变量作用域,局部命名空间,如果被提供,可以是任何映射对象

案例1:

x = 7
a = eval( '3 * x' )     #21
print(a)

b = eval('pow(2,2)')    #4
print(b)

c = eval('2 + 2')       #4
print(c)

n=81
d = eval("n + 4")       #85
print(d)

案例2:

str1 = "[{11,22},{22,33},{33,44},{44,55}]"
print(str1) #[{11,22},{22,33},{33,44},{44,55}]
print(type(str1)) #<class 'str'>

list = eval(str1)

print(list)  #[{11,22},{22,33},{33,44},{44,55}]
print(type(list)) #<class 'list'>

execfile 函数

功能:可以用来执行一个文件

语法: execfile(filename[, globals[, locals]])
filename – 文件名
globals – 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象
locals – 变量作用域,局部命名空间,如果被提供,可以是任何映射对象

返回值:返回表达式执行结果

实例:假设文件 hello.py,内容如下
print(‘runoob’);

>>>execfile(‘hello.py’)
输出:runoob

不过在 python 3 删除了这个方法,代替为

with open('hello.py','r') as f:
    exec(f.read())

file 函数

功能:用于创建一个 file 对象,它有一个别名叫 open(),更形象一些,它们是内置函数。参数是以字符串的形式传递的

语法:file(name[, mode[, buffering]])
name - - 文件名
mode - - 打开模式
buffering - - 0 表示不缓冲,如果为 1 表示进行行缓冲,大于 1 为缓冲区大小

实例:

f = file('a.txt')
str = f.read()
print(str)

filter 函数

功能:用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表

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

注意: Python2.7 返回列表,Python3.x 返回迭代器对象

语法:filter(function, iterable)
function – 判断函数
iterable – 可迭代对象

返回值:返回列表

实例1:

def is_odd(n):
    return n % 2 == 1

newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(list(newlist)) # [1,3,5,7,9]

实例2:

import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0

newlist = filter(is_sqr, range(1, 101))
print(list(newlist)) #[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

float 函数

功能:用于将整数和字符串转换成浮点数

语法:class float([x]) x 为整数或者字符串

返回值:返回浮点数

实例:

float(1)      #1.0
float(112)    #112.0
float(-123.6) #-123.6
float('123')  #字符串 123.0

format 格式化函数

功能:Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

用法:基本语法是通过 {} 和 : 来代替以前的 %

参数:format 函数可以接受不限个参数,位置可以不按顺序

实例1:

s1 = "{} {}".format("hello", "world")  # 不设置指定位置,按默认顺序  'hello world'
print(s1)

s2 = "{0} {1}".format("hello", "world")  # 设置指定位置  'hello world'
print(s2)

s3 = "{1} {0} {1}".format("hello", "world")  # 设置指定位置  'world hello world'
print(s3)

s4 = "{2} {3} {4}".format("a", "b","c","d","e")
print(s4) # c d e

实例2:

print("网站名:{name}, 地址 {url}".format(name="百度", url="www.baidu.com"))
# 通过字典设置参数
site = {"name": "maze", "url": "www.baidu.com"}
print("网站名:{name}, 地址 {url}".format(**site))

# 通过列表索引设置参数
my_list = ['maze', 'www.baidu.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

class AssignValue(object):
    def __init__(self, value):
        self.value = value
my_value = AssignValue(6)
print('value 为: {0.value}'.format(my_value))  # "0" 是可选的

实例3:

print("{:.2f}".format(3.1415926))   # 3.14
print("{:+.2f}".format(3.1415926))  # +3.14
print("{:+.2f}".format(3))          # +3.00
print("{:.0f}".format(3.1415936))   # 3
print("{:0>2d}".format(5))          # 左边补0,宽度为 2
print("{:x<4d}".format(5))          # 右边补x,宽度为 x
print("{:,}".format(100000))        # 100,000
print("{:.2%}".format(0.25))        # 25.00% 保留两位小数
print("{:.2e}".format(10000000))    # 1.00e+07
print("{:>10d}".format(10))         # 右对齐,宽度为10
print("{:<10d}".format(13))         # 左对齐,宽度为10
print("{:^10d}".format(10))         # 中间对齐,宽度为10

print('{:b}'.format(11))    #1011
print('{:d}'.format(11))    #11
print('{:o}'.format(11))    #13
print('{:x}'.format(11))    #b
print('{:#x}'.format(11))   #0xb
print('{:#X}'.format(11))   #0xB
print ("{} 对应的位置是 {{0}}".format("runoob")) #{}大括号进行转义

frozenset 函数

功能:frozenset() 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素

语法:class frozenset([iterable])
iterable – 可迭代的对象,比如列表、字典、元组等等

返回值:返回新的 frozenset 对象,如果不提供任何参数,默认会生成空集合

实例:

a = frozenset(range(10))     # 生成一个新的不可变集合
print(a) # frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
b = frozenset('runoob')
print(b) #frozenset(['b', 'r', 'u', 'o', 'n'])   # 创建不可变集合

getattr 函数

功能:getattr() 函数用于返回一个对象属性值

语法:getattr(object, name[, default])
object – 对象
name – 字符串,对象属性
default – 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError

返回值:返回对象属性值

实例

class A(object):
    bar = 1
a = A()
getattr(a, 'bar')        # 获取属性 bar 值 1
getattr(a, 'bar2')       # 属性 bar2 不存在,触发异常
'''
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'bar2'
'''
getattr(a, 'bar2', 3)    # 属性 bar2 不存在,但设置了默认值  3

globals 函数

功能: 以字典类型返回当前位置的全部全局变量

语法:globals()

参数:无

返回值:全局变量的字典

实例:

a='runoob'
print(globals()) # globals 函数返回一个全局变量的字典,包括所有导入的变量。
{
	'__name__': '__main__', '__doc__': '\nprint (abs(-10-1))\n', 
	'__package__': None, 
	'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002A97CCAE708>,
	'__spec__': None, '__annotations__': {}, 
	'__builtins__': <module 'builtins' (built-in)>,
	'__file__': 'F:/localcode/PythonProject/Base/test1.py',
	'__cached__': None, 'list1': ['01', '02', '03'],
	'dest': ['101', '102', '103'], 'unit_element': '1',
	'a': 'maze'
}

hash 函数

功能:用于获取一个对象(字符串或者数值等)的哈希值

语法:hash(object) object - - 对象

返回值:返回对象的哈希值

s1 = hash('test')            # 字符串  2314058222102390712
print(s1)

s2 = hash(1)                 # 数字  1
print(s2)

s3 = hash(str([1,2,3]))      # 集合  1335416675971793195
print(s3)

s4 = hash(str(sorted({'1':1}))) # 字典  7666464346782421378
print(s4)

所得的结果和对象的 id(),也就是内存地址有关

class Test:
    def __init__(self, i):
        self.i = i

for i in range(10):
    t = Test(1)
    print(hash(t), id(t))

输出以下
-9223371890818544680 2336579698056
-9223371890818430984 2336581517192
-9223371890818544680 2336579698056
-9223371890818430984 2336581517192
-9223371890818544680 2336579698056
-9223371890818430984 2336581517192
-9223371890818544680 2336579698056
-9223371890818430984 2336581517192
-9223371890818544680 2336579698056
-9223371890818430984 2336581517192 

help 函数

功能:函数用于查看函数或模块用途的详细说明

语法:help([object]) object - - 对象

返回值:返回对象帮助信息

实例:


help('sys')  # 查看 sys 模块的帮助  ……显示帮助信息……

help('str')  # 查看 str 数据类型的帮助  ……显示帮助信息……

a = [1, 2, 3]
help(a)  # 查看列表 list 帮助信息 ……显示帮助信息……

help(a.append)  # 显示list的append方法的帮助  …显示帮助信息……
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿的温柔香

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值