Python_常见内置函数
1. 方法

注:class(类)是具有相同的属性和方法的对象的集合。
2. 例子
(1)数据/集合类型
- str(object=‘‘); str(object=b‘‘, encoding=‘utf-8‘, errors=‘strict‘)
- int(x, base=10)
- float(x=0)
- complex(real=0, imag=0)
>>> str(123) ‘123‘ >>> str([‘a‘, ‘b‘, ‘c‘]) "[‘a‘, ‘b‘, ‘c‘]" >>> str(123).join([‘a‘, ‘b‘, ‘c‘]) ‘a123b123c‘ >>> int(‘123‘) 123 >>> float(‘123‘) 123.0 >>> (0.75).as_integer_ratio() (3, 4) >>> (1.0).is_integer() True >>> complex(1, 2) (1+2j) >>> complex(1, 2).conjugate() (1-2j)
注:str方法,详情见https://www.cnblogs.com/shz-blog/p/12426630.html
- range(stop), range(start, stop[, step])
- tuple(iterable=())
- list([iterable])
- dict(); dict(mapping); dict(iterable); dict(**kwargs)
>>> r = range(40, 1, -3)
>>> t = tuple(r)
>>> l = list(r)
>>> t
(40, 37, 34, 31, 28, 25, 22, 19, 16, 13, 10, 7, 4)
>>> l
[40, 37, 34, 31, 28, 25, 22, 19, 16, 13, 10, 7, 4]
>>> r.count(1)
0
>>> r.index(31)
3
>>> t.count(10)
1
>>> t.index(31)
3
>>> l.sort()
>>> l
[4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40]
>>> dict(a=1, b=2, c=3)
{‘a‘: 1, ‘b‘: 2, ‘c‘: 3}
>>> dict(zip(list(‘abc‘), [1, 2, 3]))
{‘a‘: 1, ‘b‘: 2, ‘c‘: 3}
>>> dict([(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)])
{‘a‘: 1, ‘b‘: 2, ‘c‘: 3}
>>> dict(a=1, b=2, c=3).items()
dict_items([(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)])注:list方法,详情见https://www.cnblogs.com/shz-blog/p/12438954.html;
dict方法,详情见https://www.cnblogs.com/shz-blog/p/12456194.html
- set([iterable])
- frozenset([iterable])
>>> s1 = set(‘hello‘)
>>> s1
{‘o‘, ‘h‘, ‘e‘, ‘l‘}
>>> s1.add(123)
>>> s1
{‘o‘, ‘l‘, ‘h‘, ‘e‘, 123}
>>> s1.discard(‘o‘)
>>> s1
{‘l‘, ‘h‘, ‘e‘, 123}
>>> s2 = set(‘lemon‘)
>>> s2
{‘o‘, ‘l‘, ‘e‘, ‘m‘, ‘n‘}
>>> s1.update(s2)
>>> s1
{‘o‘, ‘l‘, ‘h‘, ‘e‘, ‘m‘, ‘n‘, 123}>>> a = frozenset(‘hello world‘)
>>> a
frozenset({‘w‘, ‘l‘, ‘ ‘, ‘r‘, ‘o‘, ‘h‘, ‘d‘, ‘e‘})
>>> b = frozenset(range(5))
>>> b
frozenset({0, 1, 2, 3, 4})
>>> c = frozenset(range(2,7))
>>> c
frozenset({2, 3, 4, 5, 6})
>>> b.union(c) # 并集
frozenset({0, 1, 2, 3, 4, 5, 6})
>>> b.intersection(c) # 交集
frozenset({2, 3, 4})
>>> b.difference(c) # 差集
frozenset({0, 1})
>>> c.difference(b) # 差集
frozenset({5, 6})
>>> b.symmetric_difference(c) # 对称差集
frozenset({0, 1, 5, 6})
>>> b.isdisjoint(c) # 是否没有交集
False
>>> d = frozenset(range(2,5))
>>> d
frozenset({2, 3, 4})
>>> d.issubset(b) # 是否被包含
True
>>> b.issuperset(d) # 是否包含
True
>>> e = d.copy() #复制
>>> id(d) == id(e)
True- bytearray和bytes
>>> bytes()
b‘‘
>>> bytes(3)
b‘\x00\x00\x00‘
>>> bytes(‘abc‘, ‘utf-8‘)
b‘abc‘
>>> bytes([1, 2, 3])
b‘\x01\x02\x03‘
>>> b‘abcd‘.replace(b‘bc‘, b‘XY‘)
b‘aXYd‘
>>> B = b‘abc‘
>>> BA = bytearray(B)
>>> BA
bytearray(b‘abc‘)
>>> [i for i in B]
[97, 98, 99]
>>> [i for i in BA]
[97, 98, 99]
>>> B[0] = 65
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
B[0] = 65
TypeError: ‘bytes‘ object does not support item assignment
>>> BA[0] = 65
>>> BA
bytearray(b‘Abc‘)(2)操作
- format(value, format_spec=‘‘)
详情见https://www.cnblogs.com/shz-blog/p/12422194.html
- len(obj)
- sorted(iterable, key=None, reverse=False)
- reversed(sequence)
- slice(stop); slice(start, stop[, step])
>>> L = list(‘abcde‘) >>> L [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘] >>> len(L) 5 >>> sorted(L, reverse=True) [‘e‘, ‘d‘, ‘c‘, ‘b‘, ‘a‘] >>> list(reversed(L)) [‘e‘, ‘d‘, ‘c‘, ‘b‘, ‘a‘] >>> L[slice(1, 4, 2)] [‘b‘, ‘d‘]
- enumerate(iterable, start=0)
- zip(iter1 [,iter2 [...]])
- map(func, *iterables)
>>> l1 = [1, 2, 3] >>> l2 = [4, 5, 6] >>> l3 = [7, 8, 9, 10] >>> list(enumerate(l3)) [(0, 7), (1, 8), (2, 9), (3, 10)] >>> list(zip(l1, l2)) [(1, 4), (2, 5), (3, 6)] >>> list(zip(l1, l3)) [(1, 7), (2, 8), (3, 9)] >>> list(zip(*zip(l1, l3))) # *理解为解压 [(1, 2, 3), (7, 8, 9)] >>> list(map(lambda x: x * 3, l1)) [3, 6, 9] >>> list(map(lambda x, y: x + y, l1, l2)) [5, 7, 9]
(3)输入输出
- input(prompt=None)
- open(file, mode=‘r‘, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
- print(value, ..., sep=‘ ‘, end=‘\n‘, file=sys.stdout, flush=False)
>>> age = input(‘请输入年龄:‘) 请输入年龄:18 >>> age ‘18‘ >>> type(age) <class ‘str‘>
注:open的用法,详情见https://www.cnblogs.com/sesshoumaru/p/6047046.html;
文件的打开、读取等各种操作,详情见https://www.cnblogs.com/hackpig/p/8215786.html
1 >>> print(‘hello world‘, ‘hello Bunny‘, sep=‘\n‘, end=‘_‘*10) 2 hello world 3 hello Bunny__________
注:flush的用法,参考https://blog.csdn.net/Zhongjie1986/article/details/91890109
(4)数学函数
- abs(x)
- divmod(x, y)
- pow(x, y, z=None)
- round(number, ndigits=None)
- sum(iterable, start=0)
- max(arg1, arg2, *args, *[, key=func]); max(iterable, *[, default=obj, key=func])
- min(arg1, arg2, *args, *[, key=func]); min(iterable, *[, default=obj, key=func])
>>> abs(-10) 10 >>> divmod(11, 3) (3, 2) >>> pow(2, 3) 8 >>> pow(2, 3, 3) 2 >>> round(1.2345, 2) 1.23 >>> sum(range(5)) 10
>>> max(1, 2, 3)
3
>>> max(1, 2, ‘3‘)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
max(1, 2, ‘3‘)
TypeError: ‘>‘ not supported between instances of ‘str‘ and ‘int‘
>>> max(1, 2, ‘3‘, key=int)
‘3‘
>>> max(-3, 1, 2, key=abs)
-3
>>> max(‘123‘)
‘3‘
>>> max([1, 8], [2, 6], [3, 4])
[3, 4]
>>> couple = ({‘name‘: ‘Bunny‘, ‘age‘: 18, ‘salary‘: 888}, {‘name‘: ‘Twan‘, ‘age‘: 20, ‘salary‘: 666})
>>> max(couple, key=lambda x: x[‘age‘])
{‘name‘: ‘Twan‘, ‘age‘: 20, ‘salary‘: 666}
>>> max((), default=0)
0(5)编码
- bin(number), oct(number), hex(number)
- chr(i), ord(c), ascii(obj), repr(obj)
>>> bin(10) ‘0b1010‘ >>> oct(10) ‘0o12‘ >>> hex(10) ‘0xa‘ >>> chr(65) ‘A‘ >>> ord(‘A‘) 65 >>> ascii(‘hello world‘) "‘hello world‘" >>> repr(‘hello world‘) "‘hello world‘" >>> ascii(‘你好,世界‘) "‘\\u4f60\\u597d\\uff0c\\u4e16\\u754c‘" >>> repr(‘你好,世界‘) "‘你好,世界‘"
(6)判断
- bool(x), all(iterable), any(iterable), callable(object)
>>> all([‘a‘, ‘b‘, ‘c‘]) True >>> all([‘a‘, ‘b‘, ‘‘, ‘c‘]) False >>> all([]) True >>> any([0, ‘‘, False]) False >>> any([]) False >>> callable(str) True >>> callable(‘hello world‘) False
(7)迭代器
- iter(iterable); iter(callable, sentinel)
- next(iterator[, default])
- filter(function or None, iterable)
>>> for i in iter(list(‘abc‘)):
print(i)
a
b
c
>>> from random import randint
>>> def guess():
return randint(0,10)
>>> num = 1
>>> for i in iter(guess, 5):
print(‘第%s次猜测,猜测数字为:%s‘ % (num, i))
num += 1
第1次猜测,猜测数字为:3
第2次猜测,猜测数字为:1注:猜数字的例子来自http://www.imooc.com/article/287997
>>> i = iter(list(‘abc‘))
>>> next(i)
‘a‘
>>> next(i)
‘b‘
>>> next(i)
‘c‘
>>> next(i)
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
next(i)
StopIteration
>>> next(i, 0)
0>>> def is_odd(n):
return n % 2 == 1
>>> oldlist = [i for i in range(1,11)]
>>> oldlist
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> newlist = list(filter(is_odd, oldlist))
>>> newlist
[1, 3, 5, 7, 9](8)属性操作
- getattr(obj, name[, default])
- setattr(obj, name, value)
- hasattr(obj, name)
- delattr(obj, name)
>>> class Person:
name = ‘Bunny‘
age = 18
sex = ‘女‘
>>> Person.name
‘Bunny‘
>>> Person.country
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
Person.country
AttributeError: type object ‘Person‘ has no attribute ‘country‘
>>> getattr(Person, ‘age‘, 0)
18
>>> getattr(Person, ‘country‘, 0)
0
>>> setattr(Person, ‘country‘, ‘China‘)
>>> getattr(Person, ‘country‘, 0)
‘China‘
>>> delattr(Person, ‘sex‘)
>>> hasattr(Person, ‘sex‘)
False(9)辅助函数
- dir([object])
>>> dir() [‘__annotations__‘, ‘__builtins__‘, ‘__doc__‘, ‘__loader__‘, ‘__name__‘, ‘__package__‘, ‘__spec__‘] >>> dir(dict) [‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘clear‘, ‘copy‘, ‘fromkeys‘, ‘get‘, ‘items‘, ‘keys‘, ‘pop‘, ‘popitem‘, ‘setdefault‘, ‘update‘, ‘values‘]
- help([object])
>>> help(hash)
Help on built-in function hash in module builtins:
hash(obj, /)
Return the hash value for the given object.
Two objects that compare equal must also have the same hash value, but the
reverse is not necessarily true.- hash(obj)
>>> hash(‘hello world‘) -8331809543453374991 >>> hash(tuple(‘abcde‘)) 5996617995451668254
哈希的相关知识点:https://www.cnblogs.com/abdm-989/p/11329122.html
- id([object])
>>> a = ‘hello world‘ >>> b = a >>> id(a) 1873301041520 >>> id(b) 1873301041520
- memoryview(object)
>>> a = memoryview(bytearray(‘abcde‘, ‘utf-8‘)) >>> a[1] 98 >>> a[1:3] <memory at 0x0000017F63B83408> >>> a[1:3].tobytes() b‘bc‘ >>> a[1:3].tolist() [98, 99]
优点:memoryview减少内存拷贝,优化效率(详情可参考https://www.hustyx.com/python/222/)
- type(object), type(name, bases, dict)
- issubclass(cls, class_or_tuple)
- isinstance(obj, class_or_tuple)
>>> a = 2 >>> type(a) <class ‘int‘> >>> isinstance(a, int) True >>> isinstance(a, str) False >>> isinstance(a, (str, int, list)) # 是元组中的一个就返回True True
>>> class A: 2 pass >>> class B(A): 5 pass >>> issubclass(B, A) True >>> isinstance(B(), A) True >>> type(B()) == A False
(10)面向对象
- @classmethod, @staticmethod
>>> class A:
num = 0 #类属性
#类方法
@classmethod
def setNum(cls,newNum):
cls.num = newNum
#实例方法
def __init__(self):
self.age = 1 #实例属性
def setAge(self, newAge):
self.age = newAge
#静态方法
@staticmethod
def printInfo():
print(‘类方法修改类属性,实例方法修改实例属性,静态方法不访问类‘)
>>> a = A()
>>> a.setAge(18)
>>> a.age
18
>>> A.setAge(18)
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
A.setAge(18)
TypeError: setAge() missing 1 required positional argument: ‘newAge‘
>>> A.setNum(100)
>>> A.num
100
>>> A.printInfo()
类方法修改类属性,实例方法修改实例属性,静态方法不访问类- property(fget=None, fset=None, fdel=None, doc=None); @property
效果:
>>> c = C()
>>> c.x = 10
>>> c.x
10
>>> del c.x
>>> c.x
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
c.x
File "<pyshell#13>", line 5, in x
return self._x
AttributeError: ‘C‘ object has no attribute ‘_x‘方式1:
1 >>> class C(object): 2 def getx(self): return self._x 3 def setx(self, value): self._x = value 4 def delx(self): del self._x 5 x = property(getx, setx, delx, "I‘m the ‘x‘ property.")
方式2:
>>> class C(object):
@property
def x(self):
"I am the ‘x‘ property."
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x- super
>>> class A:
def add(self, x):
print(x+1)
>>> class B(A):
def add(self, x):
super().add(x)
>>> B().add(2)
3- globals, locals, vars([object])
>>> word = ‘hello world‘
>>> def test(x):
y = 1
print(locals())
>>> test(2)
{‘x‘: 2, ‘y‘: 1}
>>> globals()
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <class ‘_frozen_importlib.BuiltinImporter‘>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘word‘: ‘hello world‘, ‘test‘: <function test at 0x0000023BE4CEEF28>}
>>> class A:
a = 1
>>> vars(A)
mappingproxy({‘__module__‘: ‘__main__‘, ‘a‘: 1, ‘__dict__‘: <attribute ‘__dict__‘ of ‘A‘ objects>, ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘A‘ objects>, ‘__doc__‘: None})(11)可执行对象
- eval(source, globals=None, locals=None)
- exec(source, globals=None, locals=None)
- compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
>>> eval(‘2 * 3 + 4‘)
10
>>> exec(‘print("hello world")‘)
hello world
>>> eval_code = compile(‘2 * 3 + 4‘, ‘‘, ‘eval‘)
>>> eval_code
<code object <module> at 0x00000269270686F0, file "", line 1>
>>> eval(eval_code)
10
>>> exec_code = compile(‘print("hello world")‘, ‘‘, ‘exec‘)
>>> exec_code
<code object <module> at 0x0000026927074150, file "", line 1>
>>> exec(exec_code)
hello world需要注意的是,exec函数和eval函数都是将用户提供的字符串作为代码执行,将无法控制代码的行为,会带来严重的安全隐患,使用的时候要慎重。
>>> exec(‘abs="xyz"‘)
>>> abs(-1)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
abs(-1)
TypeError: ‘str‘ object is not callable报错的原因是使用exec函数将‘xyz‘赋值给了abs,abs不再是求绝对值的函数了。为了避免污染命名空间,在调用exec函数时,可以给它传递第二个参数——命名空间。
>>> scope = {}
>>> exec(‘abs="xyz"‘, scope)
>>> abs(-1)
1
>>> scope[‘abs‘]
‘xyz‘注:参考了https://www.cnblogs.com/lucky-heng/p/10161190.html
题外话:关于内置函数,发现了一个非常详细的介绍(https://www.cnblogs.com/sesshoumaru/p/6140987.html),这个博主还对每个函数分别用一篇随笔来介绍。写到一半,看到这么详尽的博客,瞬间就有点不想写了,不过我写博客主要还是为了方便自己日后查阅,不够详细的地方可以移步上面这个博主。本文总体参考了官方说明文档、内置函数介绍英文版(https://docs.python.org/3/library/functions.html#classmethod)及其翻译版(http://www.beixiongxiong.com/course/bxx_bzk_02/2084/)。