python--内置函数

一、内置函数

二、内置函数演示

1、abs(x)

功能:取数的绝对值

>>> abs(-1)  #取-1的绝对值
1


#---------------------------------------------------------------------------------
2、all(iterable)

功能:如果这个可迭代的元素都为真,则返回真(非0的就为真,负数也是为真)

>>> all([0,1,3])   #有0,说明为假
False
>>> all([1,-5,6])  #负数也是为真
True


#---------------------------------------------------------------------------------
3、any(iterable)

功能:可迭代的元素中,有一个为真,则返回真,空列表返回假。

>>> any([0,1,2])  #有一个为真,则为真
True
>>> any([])  #空列表为假
False


#---------------------------------------------------------------------------------
4、ascii(object)

功能:把内存对象变成一个可打印的字符串格式

>>> ascii([1,2,3,4])
'[1, 2, 3, 4]'


#---------------------------------------------------------------------------------
5、bin(x)

功能:把一个整数转换成二进制

>>> bin(300)  #把300转换成二进制
'0b100101100'
>>> bin(1)
'0b1'


#---------------------------------------------------------------------------------
6、bool([x])

功能:返回一个布尔值,空列表为假,不为空为真

>>> bool([])   #空列表
False
>>> bool([1,2])   #不为空列表
True
>>> bool([0])
True


#---------------------------------------------------------------------------------
7、bytearray[source[, encoding[, errors]]]

功能:字节数组,并且可以修改二进制的字节

>>> b = bytearray("abcd",encoding="utf-8")  #声明一个字节数组
>>> b[0]  #打印第一个元素的ascii值,也就是'a'对应的ascii值
97
>>> b[0] = 100  #修改时,只能赋值对应字符的ascii值
>>> b
bytearray(b'dbcd')   #发现字节数组值被修改


#---------------------------------------------------------------------------------
8、bytes([source[, encoding[, errors]]])

功能:把字符串转换成字节

>>> b = bytes("abcd",encoding="utf-8")  #声明字节
>>> b
b'abcd'
>>> b[0]   #访问到'a'字符对应的ASCII值
97
>>> b[0]=100    #不可以修改里面的值,不然会报错
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment


#---------------------------------------------------------------------------------
9、callable(object)

功能:判断一个对象是否可以被调用,只有在后面有括号的,表示可以调用,比如:函数,类。

>>> callable([])  #列表后面不加括号
False
>>> def sayhi():pass  #定义一个函数
>>> callable(sayhi)  #函数调用,后面需要加括号
True


#---------------------------------------------------------------------------------
10、chr(i)

功能:通过ascii的值,找到对应的字符

>>> chr(97)
'a'


#---------------------------------------------------------------------------------
11、classmethod()

功能:修饰符对应的函数不需要实例化 

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


#---------------------------------------------------------------------------------
12、compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

功能:用于把代码编译的一个过程,这个基本用不到

>>> code = """1+3/2*6"""  
>>> py_object = compile(code,'','eval')  #把代码转换为字符串
>>> eval(py_object)  #执行
10.0


#---------------------------------------------------------------------------------
13、complex([real[, imag]])

功能:返回一个复数,我们几乎用不到。
>>> complex('1+2j')
(1+2j)


#---------------------------------------------------------------------------------
14、delattr(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)

('x = ', 10)
('y = ', -5)
('z = ', 0)
--删除 z 属性后--
('x = ', 10)
('y = ', -5)
Traceback (most recent call last):
  File "test.py", line 22, in <module>
    print('z = ',point1.z)
AttributeError: Coordinate instance has no attribute 'z'


#---------------------------------------------------------------------------------

15、dict(**kwarg)、dict(mapping, **kwarg)、dict(iterable, **kwarg)

功能:返回一个字典
>>> dict()  #定义一个字典
{}
>>> dict(name='zhangqigao',age=18)   #传入非固定关键字参数
{'name': 'zhangqigao', 'age': 18}
>>> dict([('name','zhangqigao'),('age',18)])   #传入一个列表
{'name': 'zhangqigao', 'age': 18}
>>> dict([['name','zhangqigao'],['age',18]])    #传入一个列表
{'name': 'zhangqigao', 'age': 18}
 

#---------------------------------------------------------------------------------
16、dir([object])

功能:看一个对象有哪些方法

>>> name = []
>>> dir(name)  #显示name下的所有的方法
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__', '__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']


#---------------------------------------------------------------------------------
17、divmod(a,b)

功能:地板除,获得一个元组,元组第一个元素是商,第二个元素是余数。
>>> divmod(5,2)
(2, 1)    #2是商,1是余数


#---------------------------------------------------------------------------------
18、enumerate(iterable,start=0)

功能:获取一个列表,列表中的每个元素都是一个元组,元组的第一个数是iterable的索引,第二个数是iterable的元素。
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]


#---------------------------------------------------------------------------------
19、eval(expression, globals=None, locals=None)

功能:把字典类型的字符串变成字典,把一个整数类型的字符变成int类型,或者加减乘除这种简单转换成表达式。
>>> eval('1')  #字符类型转换成int类型
1
>>> eval("1+3/2*6")   #字符串转换为表达式
10.0


#---------------------------------------------------------------------------------
20、exec(object[, globals[, locals]])

功能:有语句的和复杂的语句的字符串转换成表达式

code = '''
def timmer(func):  #timmer(test1) func=test1
    def deco(*args,**kwargs):
        res = func(*args,**kwargs)   #run test1()
        return res
    return deco
 
@timmer
def test1():
    print("in the test1")
    return "from the test1"
 
res = test1()
print(res)
'''
 
exec(code) 
 
#输出
in the test1
from the test1


#---------------------------------------------------------------------------------
21、filter(function, iterable)

功能:通过function过滤条件,去获取iterable中你想要的数据。

>>> res = filter(lambda n:n>5,range(10)) 
>>> res     #得到一个迭代器
<filter object at 0x0000000003093BE0>
>>> for i in res:
    print(i)


#---------------------------------------------------------------------------------
22、map(function, iterable)

功能:对传入的每一个值进行处理,处理完了再返回,再把原来的结果覆盖掉。

>>> res = map(lambda n:n*2,range(5))  #n*2是处理方式
>>> res
<map object at 0x00000000031B4BE0>
>>> for i in res:
    print(i)
0
2
4
6
8


#---------------------------------------------------------------------------------
23、reduce(function,iterable)

功能:把一组可迭代序列通过function函数操作,元素之间相加或者相乘操作。
>>> from functools import reduce
>>> res = reduce(lambda x,y:x+y,range(10))  #x+y的值赋给x,rang(10)中的每个元素赋给y
>>> res
45
>>> res = reduce(lambda x,y:x*y,range(1,10)) #x*y的值赋给x,rang(10)中的每个元素赋给y
>>> res
362880


#---------------------------------------------------------------------------------
24、float([x])

功能:把一个浮点类型的字符串转换为浮点类型的数据。

>>> float('+1.23')
1.23
>>> float('   -12345
')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf

#---------------------------------------------------------------------------------
25、format(value[, format_spec])

功能:格式话字符串,以前随笔中有介绍

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'


#---------------------------------------------------------------------------------
26、frozenset([iterable])

功能:把集合变成一个不可变的集合

>>> res = frozenset([1,2,3,4,3])
>>> res
frozenset({1, 2, 3, 4})   #去重的,不可变的集合
>>> dir(res)   #没有可变的方法
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__iter__', '__le__',
 '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__',
'__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__',
'__subclasshook__', '__xor__', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset',
'issuperset', 'symmetric_difference', 'union']
 注:set()是可变的


#---------------------------------------------------------------------------------
27、getattr(object, name[, default])

功能:类中的反射函数
>>> 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


#---------------------------------------------------------------------------------
28、globals()

功能:返回当前这个python文件中的所有变量的key-value,变量是key,值是value

print(globals())
 
#输出
{'__spec__': None, '__name__': '__main__', '__file__': 'D:/PycharmProjects/pyhomework
/day4/内置函数/内置函数.py', '__doc__': None, '__package__': None, '__loader__':
<_frozen_importlib_external.SourceFileLoader object at 0x0000000000695B00>,
'__cached__': None, '__builtins__': <module 'built
注:可以判断一个文件中的变量是否存在,而globals()只能打印全局变量


#---------------------------------------------------------------------------------
29、hash(object)

功能:反射出一个对象的对应的hash值。

>>> hash('zhangqigao')
2313972277536963491
>>> hash(255)
255
>>> hash('a')
6806508886604307842


#---------------------------------------------------------------------------------
30、ord(c)

功能:根据字符,找到对应的ascii值
>>> ord('a')
97


#---------------------------------------------------------------------------------
31、help([object])

功能:显示对象的帮助信息

>>> res = []  #定义一个列表
>>> help(res)   #打印帮助信息
Help on list object:
 
class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 | 
 |  Methods defined here:
 | 
 .....


#---------------------------------------------------------------------------------
32、hex(x)

功能:把一个数字转成16进制

>>> hex(255)
'0xff'
>>> hex(10)
'0xa'


#---------------------------------------------------------------------------------
33、id(object)
功能:返回对象的内存地址

>>> id('zhangqigao')
50993136   #'zhangqigao'这个字符串的内存地址


#---------------------------------------------------------------------------------
34、input([prompt])

功能:输入字符串

>>> s = input('--> ') 
--> Monty Python's Flying Circus  #输入的内容
>>> s 
"Monty Python's Flying Circus"


#---------------------------------------------------------------------------------
35、int(x)

功能:把其他数据类型强制转换成int类型

>>> int('10')
10


#---------------------------------------------------------------------------------
36、isinstance(object, classinfo)

功能:这个在迭代器中使用,详情:猛击这里

>>> a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list))    # 是元组中的一个返回 True
True


#---------------------------------------------------------------------------------
37、issubclass(class, classinfo)

功能:判断是否是一个子类,这个后续讲到类那边会讲

class A:
    pass
class B(A):
    pass
    
print(issubclass(B,A))    # 返回 True


#---------------------------------------------------------------------------------
38、iter(object[, sentinel])

功能:把一个普通序列转成迭代器

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)


#---------------------------------------------------------------------------------
39、len(s)

功能:计算序列或者字符串的长度

>>> len("zhangqigao")  #字符串的长度
10
>>> len([1,2,3,4,5])  #列表的长度
5


#---------------------------------------------------------------------------------
40、list([iterable])

功能:把其他序列转换成一个列表

>>> list((1,2,3,4,5))   #把一个元组转换为一个列表
[1, 2, 3, 4, 5]


#---------------------------------------------------------------------------------
41、locals()

功能:打印局部变量

def test():
    locals_var = 333
    print(locals())   #只打印局部变量
 
test()
print(globals().get("locals_var"))  #只能打印全局变量
 
#输出
 
{'locals_var': 333}
None


#---------------------------------------------------------------------------------
42、max(iterable, *[, key, default])
能:返回列表重点额最大值

>>> max([1,2,3,4,5])
5


#---------------------------------------------------------------------------------
43、min(iterable, *[, key, default])

功能:返回列表中的最小值

>>> min([1,2,3,4,5])
1


#---------------------------------------------------------------------------------
44、memoryview(obj)

功能:函数返回给定参数的内存查看对象,暂时用不到
>>> v = memoryview('abcefg')
>>> v[1]
'b'
>>> v[-1]
'g'
>>> v[1:4]
<memory at 0x77ab28>
>>> v[1:4].tobytes()
'bce'


#---------------------------------------------------------------------------------
45、next(iterator[, default])

功能:返回迭代器的下一个值,相当于__next__()方法,如果迭代最后一个数据之后没有值了,则会抛出一个StopIteration异常

>>> a = iter([1,2])
>>> next(a)
1
>>> next(a)
2
>>> next(a)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration


#---------------------------------------------------------------------------------
46、object

功能:python中一切皆对象,每一个对象都有它的属性和方法


#---------------------------------------------------------------------------------
47、oct(x)

功能:把一个数转成8进制

>>> oct(7)
'0o7'
>>> oct(8)
'0o10'
>>> oct(15)
'0o17'
>>> oct(16)
'0o20'


#---------------------------------------------------------------------------------
48、open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

功能:文件操作


#---------------------------------------------------------------------------------
49、pow(x, y[, z])

功能:返回多少次幂

>>> pow(2,3)  #相当于2**3
8


#---------------------------------------------------------------------------------
50、print(*objects, sep=' ', end='
', file=sys.stdout, flush=False)

功能:打印

>>> print("zhangqigao")
zhangqigao


#---------------------------------------------------------------------------------
51、property(fget=None, fset=None, fdel=None, doc=None)

功能:类方法。类内部装饰器

>>> class C:
>>>     def __init__(self):
>>>         self._x = None
>>> 
>>>     def getx(self):
>>>         return self._x
>>> 
>>>     def setx(self, value):
>>>         self._x = value
>>> 
>>>     def delx(self):
>>>         del self._x
>>> 
>>>     x = property(getx, setx, delx, "I'm the 'x' property.")


#---------------------------------------------------------------------------------
52、range(stop)、range(start, stop[, step])

功能:生成一个迭代器

>>> range(5)
range(0, 5)
>>> range(1,5)
range(1, 5)
>>> range(1,5,2)
range(1, 5, 2)


#---------------------------------------------------------------------------------
53、repr(object)

功能:把代码转成字符串对象

>>> s = 'RUNOOB'
>>> repr(s)
"'RUNOOB'"
>>> dict = {'runoob': 'runoob.com', 'google': 'google.com'};
>>> repr(dict)
"{'google': 'google.com', 'runoob': 'runoob.com'}"


#---------------------------------------------------------------------------------
54、reversed(seq)

功能:反转一个序列,跟列表中的reversed方法是一样的

>>> reversed([1,2,3,4,5])
<list_reverseiterator object at 0x00000000030A2588>  #变成一个迭代器
>>> for i in  reversed([1,2,3,4,5]):
...     print(i)
...    
5
4
3
2
1


#---------------------------------------------------------------------------------
55、round(number[, ndigits])

功能:保留float数据类型位数

>>> round(1.23344,2)  #保留两位
1.23


#---------------------------------------------------------------------------------
56、set([iterable])

功能:创建一个集合

>>>x = set('runoob')
>>> y = set('google')
>>> x, y
(set(['b', 'r', 'u', 'o', 'n']), set(['e', 'o', 'g', 'l']))   # 重复的被删除
>>> x & y         # 交集
set(['o'])
>>> x | y         # 并集
set(['b', 'e', 'g', 'l', 'o', 'n', 'r', 'u'])
>>> x - y         # 差集
set(['r', 'b', 'u', 'n'])


#---------------------------------------------------------------------------------
57、setattr(object, name, value)

功能:类的反射方法

>>> class A(object):
...     bar = 1
... 
>>> a = A()
>>> getattr(a, 'bar')          # 获取属性 bar 值
1
>>> setattr(a, 'bar', 5)       # 设置属性 bar 值
>>> a.bar
5


#---------------------------------------------------------------------------------
58、slice(stop),slice(start, stop[, step])

功能:序列的切片

>>> a = [1,2,3,4,5,6]
>>> a[slice(1,3)]
[2, 3]
>>> a[1:3]
[2, 3]


#---------------------------------------------------------------------------------
59、sorted(iterable[, key][, reverse])

功能:对一个序列进行排序

>>> sorted([5,3,2,6,8])
[2, 3, 5, 6, 8]
>>> a = {1:5,6:8,3:6}
>>> sorted(a)  #默认是按key排序
[1, 3, 6]
>>> sorted(a.items())  #按key排序
[(1, 5), (3, 6), (6, 8)]
>>> sorted(a.items(),key = lambda x:x[1])  #按value排序
[(1, 5), (3, 6), (6, 8)]


#---------------------------------------------------------------------------------
60、 str(object)

功能:把其他数据类型转换为字符串

>>> str(1)
'1'


#---------------------------------------------------------------------------------
61、sum(iterable[, start])

功能:求一个列表的和

>>> sum([1,2,3,4,5,6])
21


#---------------------------------------------------------------------------------
62、super([type[, object-or-type]])

功能:这个是类的继承,新式类

>>> class A:
>>>      def add(self, x):
>>>          y = x+1
>>>          print(y)
>>> class B(A):
>>>     def add(self, x):
>>>         super().add(x)
>>> b = B()
>>> b.add(2)  # 3


#---------------------------------------------------------------------------------
63、tuple([iterable])

功能:把其他序列转换为一个元组

>>> tuple([1,2,3,4,5])
(1, 2, 3, 4, 5)


#---------------------------------------------------------------------------------
64、type(object) 、type(name, bases, dict)

功能:查看一个对象的数据类型

>>> a = 'zhangqigao'
>>> type(a)
<class 'str'>
注:一切数据类型都是有type()方法产生,它是一切数据类型的根。


#---------------------------------------------------------------------------------
65、vars([object])

功能:返回对象的所有属性

>>> print(vars())
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> class Runoob:
...     a = 1
... 
>>> print(vars(Runoob))
{'a': 1, '__module__': '__main__', '__doc__': None}
>>> runoob = Runoob()
>>> print(vars(runoob))
{}


#---------------------------------------------------------------------------------
66、zip(*iterables)

功能:zip中文意思是拉链的意思,把两个序列一一对应起来。

>>> a = [1,2,3,4]
>>> b=['a','b','c','d']
>>> for i in zip(a,b):
...     print(i)
...    
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
 注:如果a的元素比b的多,则按照元素最少的那个来


#---------------------------------------------------------------------------------
67、__import__(name, globals=None, locals=None, fromlist=(), level=0)

功能:当导入的模块是一个字符串时,用__import__()

>>> import os
>>> __import__('os') 
<module 'os' from 'D:\Python\Python35\lib\os.py'>
View Code

更多详情:点击

原文地址:https://www.cnblogs.com/doumingyi/p/12462142.html