Python标准库(3.x): 内建函数扫盲

Built-in Functions
abs()dict()help()min()setattr()
all()dir()hex()next()slice()
any()divmod()id()object()sorted()
ascii()enumerate()   
input()oct()staticmethod() 
bin()eval()int()open()str()
bool()exec()isinstance() ord()sum()
bytearray()filter()issubclass() pow()super()
bytes()float()iter()print()tuple()
callable() format()len()property()    
type()
chr()frozenset()list()range()vars()
classmethod() getattr()locals()repr()zip()
compile()globals()map()reversed()   
complex()hasattr()max()round()  
delattr()hash()memoryview()set() 

 

abs(x)

  求一个数的绝对值。

>>> abs(13)
13
>>> abs(-15)
15

all(iterable)

  如果迭代器中的所有值都为“真”则返回 True, 否则返回 False

  注意: 如果迭代器为空,返回 True

>>> all([1,1,1])
True
>>> all([1,0,1])
False
>>> all([])
True

any(iterable)

  如果迭代器中的任意一个值为“真”则返回 True, 否则返回 False

  注意: 如果迭代器为空,返回 False

>>> any([1,0,0])
True
>>> any([0,0,0])
False
>>> any([])
False

ascii(object)

  该函数返回表示对象的可打印ascii字符串,如果字符串中含有非ascii字符,则以\x, \u 或者 \U 编码来表示

  函数其实是返回了对象的 __repr__() 方法的值

>>> a = 123
>>> a.__repr__()
'123'
>>> ascii(a)
'123'
>>> 
>>> b = 'test'
>>> b.__repr__()
"'test'"
>>> ascii(b)
"'test'"
>>>
>>> class MyTest:
...     def __repr__(self):
...         return 'Hello, world.'
... 
>>> t = MyTest()
>>> t.__repr__()
'Hello, world.'
>>> ascii(t)
'Hello, world.'

bin(x)

  将整型转换为二进制的字符串,字符串以'0b' 开头.

  不过说是将整型转换为二进制,其实是将对象的__index__() 方法返回的值转换为二进制字符串

  注意: 如果对象没有__index__() 方法,将会产生异常

>>> bin(11)
'0b1011'
>>> class MyTest():
...     def __index__(self):
...         return 5
... 
>>> t = MyTest()
>>> bin(t)
'0b101'

 bool(x)

  如果对象为“真”则返回 True, 否则返回 False

>>> bool(0)
False
>>> bool(1)
True

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

  创建一个 “可变的” byte数组,可以使用整型,字符串和迭代器来初始化

  参数为字符串时,字符串中的每一个字符将转换为数组的元素,因此需要提供编码类型,类似utf-8, ascii

  参数为整型时,整形值将作为数组的初始化大小,数组的元素则初始化为0

  参数为迭代器时,迭代器的每一个元素将作为数组的元素,因此迭代器的值必须为0-255的整型,否则将产生异常。

>>> a = bytearray(10)
>>> a
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> a[0]
0
>>> len(a)
10
>>> 
>>> b = bytearray('abc', 'utf-8')
>>> b
bytearray(b'abc')
>>> b[0]
97
>>> 
>>> c = bytearray(range(1,5))
>>> c
bytearray(b'\x01\x02\x03\x04')
>>> c[0]
1
>>> 
>>> d = bytearray([1,2,3])
>>> d
bytearray(b'\x01\x02\x03')
>>> d[1] = 20
>>> d
bytearray(b'\x01\x14\x03')

bytes([source[, encoding[, errors]]])

  bytesbytearray的一个不可变的版本,其他的可以参考bytearray

>>> d = bytes([1,2,3])
>>> d
b'\x01\x02\x03'
>>> d[1] = 20
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment

callable(object)

  判断对象是否可以调用,如果可以则返回 True, 否则返回 False

  是可调用的,调用后返回一个的实例。对象如果包含了__call__() 方法也是可调用的。

  其实,只要可以写成 object() 的,都是callable

>>> def foo():
...     pass
... 
>>> callable(foo)
True
>>> 
>>> class MyTest:
...     def __call__(self):
...         pass
... 
>>> callable(MyTest)
True
>>> a = MyTest()
>>> callable(a)
True
>>> 
>>> b = 1
>>> callable(b)
False

 chr(i)

  返回Unicode对应的字符。

  参数范围为 0 -- 1114111, 超过此范围将产生异常

>>> chr(97)
'a'
>>> chr(1666)
'ڂ'
>>> chr(1200000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: chr() arg not in range(0x110000)

classmethod(function)

  一般作为函数装饰器 @classmethod

  将类中的一个方法指定为类方法。被指定的类方法第一个参数必须为cls(方法所在的类)

  类方法的调用可以直接通过类调用,即C.f(); 也可以通过实例调用,即C().f()

  类方法有一个比较方便的用处就是作为类似C++中的初始化函数重载

class MyTest():
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day 

    @classmethod
    def from_string(cls, date_string):
        year, month, day = map(int, date_string.split('-'))
        return cls(year, month, day)
    
    def output(self):
        print('Birthday: {}-{}-{}'.format(self.year, self.month, self.day))



>>> a = MyTest(1989, 12, 26)
>>> a.output()
Birthday: 1989-12-26
>>> 
>>> b = MyTest.from_string('1990-1-1')
>>> b.output()
Birthday: 1990-1-1

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

  该函数将含有python语句的字符串编译成可执行的字节码,编译的结果配合 eval, 或 exec 使用。

  source -- 需要编译的字符串

  filename -- 存储字符串的文件

  mode -- 'eval' 配合 eval 使用, 'exec' 配合多语句的 exec 使用,'single' 配合单语句的 exec 使用

  注:实测中,编译的时候会判断mode, 但是执行的时候使用 exec 或者 eval,结果一样

>>> a = compile('1+2', filename='',  mode='eval')
>>> eval(a)
3
>>> 
>>> b = compile('for i in range(3): print(i)', filename='', mode='exec')
>>> exec(b)
0
1
2
>>> 
>>> c = compile('print("Hello, world.")', filename='', mode='exec')
>>> exec(c)
Hello, world.

complex([real[, imag]])

  返回一个复数。复数值为  real + imag*1j

  参数也可以为一个表示复数的字符串,但是字符串中不能有空格。使用字符串作为参数时,没有第二个参数。

  注1: 两个参数的缺省值均为0

  注2: 直接用复数表达式 a+bj 创建的对象也是 complex 类型

>>> a = complex(1, 2)
>>> a
(1+2j)
>>> 
>>> b = 2+3j
>>> type(b)
<class 'complex'>
>>> 
>>> c = complex('5+6j')
>>> c
(5+6j)
>>> 
>>> d = complex(1+2j, 1+2j)
>>> d
(-1+3j)

delattr(object, name)

  删除对象的一个属性(不能是对象的方法),但是不会影响该类的其他对象。同 del object.name

  注: 参数 name 是一个字符串

>>> class MyTest():
...     def __init__(self):
...         self.test = 'test'
... 
>>> a = MyTest()
>>> a.test
'test'
>>> b = MyTest()
>>> b.test
'test'
>>> delattr(a, 'test')
>>> a.test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyTest' object has no attribute 'test'
>>> 
>>> b.test
'test'

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

  创建并返回一个字典对象。初始化参数可以有三种传入方式。

  关键字方式,将直接根据关键字生成字典

  迭代器方式,迭代器中的对象必须只有两个元素,第一个元素将作为key,第二个作为值

  映射方式,其实也是一种迭代器方式

  注: 当然也可以直接使用字典作为参数来初始化

>>> dict(one=1, two=2, three=3)
{'two': 2, 'one': 1, 'three': 3}
>>> 
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3]))
{'one': 1, 'two': 2, 'three': 3}
>>> 
>>> dict([('one', 1), ('two', 2), ('three', 3)])
{'one': 1, 'two': 2, 'three': 3}
>>> 
>>> dict({'one':1, 'two':2, 'three':3})
{'one': 1, 'two': 2, 'three': 3}

dir([object])

  很有用的帮助函数。显示当前命名空间,对象或者类的所有属性和方法。

  object 可以为对象或者类,如果省略表示当前的命名空间

>>> class MyTest():
...     pass
... 
>>> def foo():
...     pass
... 
>>> a = 1
>>> 
>>> dir()
['MyTest', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'foo']
>>> 
>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
>>> 
>>> d = dict()
>>> dir(d)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__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']

divmod(a, b)

  返回 (a // b, a % b) 的元组

  注:a,b可以为整型或者浮点型,但是不能是复数

>>> divmod(7, 3)
(2, 1)
>>> 
>>> divmod(4.3, 1.5)
(2.0, 1.2999999999999998)
>>> 
>>> (4.3 // 1.5, 4.3 % 1.5)
(2.0, 1.2999999999999998)

enumerate(iterable, start=0)

  返回一个可迭代的枚举类型。

  迭代器中的对象,第一个元素为序号(默认从start=0开始),第二个元素为传入迭代器中的对象。

  注: 多用于for遍历过程中,需要同时得到序号的情况。

>>> names = ['Tom', 'Jack', 'Lily']
>>> for i, name in enumerate(names, start=1):
...     print(i ,name)
... 
1 Tom
2 Jack
3 Lily

eval(expression, globals=None, locals=None)

  将一个表示python表达式的字符串编译成python语句并执行(慎用!

  返回值,如果传入参数是字符串或者mode='eval'编译的字节码,则返回交互式运行结果,否则返回None

  globalslocals为高级用法,此处不展开。默认使用当前命名空间。

  注1: 语句必须是单条语句

  注2: 字符串中可以带入变量,但变量必须在命令空间中定义。

  注3: 可以配合compile()使用

>>> eval('2+5')
7
>>> x = 3
>>> eval('x**2 + 3*x + 5')
23

 exec(object, [globals[, locals]])

  将一个表示python表达式的字符串编译成python语句并执行(慎用!

  返回值为None

  globalslocals为高级用法,此处不展开。默认使用当前命名空间。

  注1: 语句可以是多条

  注2: 字符串中可以带入变量,但变量必须在命令空间中定义。

  注3: 可以配合compile()使用

>>> exec('for i in range(5): print(i)')
0
1
2
3
4

filter(function, iterable)

  将一个可迭代的对象按传入的函数进行过滤。函数返回 True 的元素将保留,其它将被过滤掉。

>>> a = [1,2,3,4,5,6,7,8,9]
>>> list(filter(lambda x: x % 2, a))
[1, 3, 5, 7, 9]

float([x])

  创建并返回一个浮点型的对象。

  x可以为一个数或者一个表示浮点数的字符串,缺省值为0

>>> float(3)
3.0
>>> float('1.23')
1.23

format(value [, format_spec])

  将value按格式化转化为字符串,并返回。

  目前较多的用法是调用字符串的format方法。

  format_spec 指定格式化方式,此处不展开(将会有专题博文)。

>>> format(10, 'b')
'1010'
>>> format('555', '0>5')
'00555'

frozenset([iterable])

  传入一个可迭代的对象,创建一个不可变的集合。除了元素不能添加删除外,其他和可变集合类似。

  如果没有参数,则创建一个空集合。

>>> a = frozenset([1,2,2,3,4,5])
>>> a
frozenset({1, 2, 3, 4, 5})
>>> 2 in a
True

getattr(object, name [, default])

  获取对象的一个属性的值。

  如果对象存在该属性则返回属性值。

  如果属性不存在,当传了default时返回default的值,否则产生异常。

  注:参数 name 是一个字符串

>>> class MyTest():
...     def __init__(self):
...         self.test = 'test'
... 
>>> a = MyTest()
>>> getattr(a, 'test')
'test'
>>> getattr(a, 'foo', 'attr not exist')
'attr not exist'
>>> 
>>> getattr(a, 'foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyTest' object has no attribute 'foo'

globals()

  返回当前全局域的{对象: 值} 字典

>>> globals()
{'__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__doc__': None, 'a': <__main__.MyTest object at 0x7f04880fb780>, '__spec__': None, 'MyTest': <class '__main__.MyTest'>}

hasattr(object, name)

  判断一个对象是否存在指定的属性。存在返回 True, 否则返回 False

  注: 参数name 是一个字符串

>>> class MyTest():
...     def __init__(self):
...         self.test = 'test'
... 
>>> a = MyTest()
>>> hasattr(a, 'test')
True
>>> hasattr(a, 'foo')
False

hash(object)

  返回一个对象的hash值,如果对象不可hash会产生异常。

>>> hash(10)
10
>>> 
>>> hash('test')
2595417156033713210
>>> 
>>> hash((1,2,3))
2528502973977326415
>>> 
>>> hash([1,2,3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

help([object])

  显示对象的帮助信息。如果没有参数则进入帮助的交互模式。

>>> help(eval)

Help on built-in function eval in module builtins:

eval(source, globals=None, locals=None, /)
    Evaluate the given source in the context of globals and locals.
    
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

hex(x)

  返回x的16进制字符串,字符串以'0x'开头,字符串中的字符都以小写形式表示。

  当x不是一个int型对象时,则对象必须定义一个__index__() 方法,则返回整型值,否则将产生异常。

>>> hex(64)
'0x40'
>>> hex(-10)
'-0xa'

id(object)

  返回对象的内部ID值。

>>> id(123)
10923328
>>> id('test')
140589176043704
>>> id([1,2,3])
140589199591816

 input([prompt])

  接收标准输入转为字符串并返回。

  prompt 为输入提示字符串,可以省略。

  注:如果读到 EOF 将产生异常。

>>> s = input('Enter: ')
Enter: hello
>>> s
'hello'

 int(x=0)  int(x, base=10)

  返回一个整型数。输入参数可以是一个数或者一个字符串(当然可以是其他对象,但这里不讲解这种非主流用法)。

  参数为一个数时,返回对象的__int__()方法的值,对于整型对象就是自身的值,对于浮点型对象就是整数部分。

  参数为一个字符串时,字符串必须表示一个2、8、10、16进制,并传入相应的base值。

>>> int(3)
3
>>> int(1.25)
1
>>> int('101', 2)
5
>>> int('54', 8)
44
>>> int('123', 10)
123
>>> int('F3', 16)
243

 isinstance(object, classinfo)

  判断对象是否属于指定的类。(可以配合 type 使用)

  注1: 如果指定类是当前对象的父类,判断结果也是 True

  注2: 如果 classinfo 参数是一个元组,那么只要对象属于其中的一个类即返回 True

>>> a = 12
>>> b = 25
>>> isinstance(a, int)
True
>>> isinstance(a, type(b))
True
>>> class A:
...     pass
... 
>>> class B(A):
...     pass
... 
>>> a = A()
>>> b = B()
>>> isinstance(a, A)
True
>>> isinstance(b, B)
True
>>> isinstance(a, B)
False
>>> isinstance(b, A)
True
>>> isinstance(a, (A,B))
True

issubclass(class, classinfo)

  判断一个类是否为指定类的子类。

  注1: 类都是自身的子类

  注2: 如果 classinfo 参数是一个元组,那么只要类属于其中一个类的子类即返回 True

>>> class A:
...     pass
... 
>>> class B(A):
...     pass
... 
>>> issubclass(B, A)
True
>>> issubclass(A, B)
False
>>> issubclass(A, A)
True
>>> issubclass(A, (A,B))
True

iter(object [, sentinel])

  返回一个迭代器对象,用于遍历,一般与 next() 配合使用。

  如果 sentinel 参数没有传入则 object 必须是一个可迭代的对象。

  如果 sentinel 参数有值,则object 必须是一个 callable 的对象,此时的遍历将重复调用object, 直到返回值等于 sentinel(将产生StopIteration异常)

>>> it = iter([1,2,3])
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 
>>> for i in iter([1,2,3]):
...     print(i)
... 
1
2
3
>>> f = open('test.txt', 'r')
>>> itf = iter(f.readline, '')
>>> next(itf)
'test line 1\n'
>>> next(itf)
'test line 2\n'
>>> next(itf)
'test line 3\n'
>>> next(itf)
'\n'
>>> next(itf)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> f.close()

len(s)

  返回对象的长度。对象一般是一个序列和一个集合。

  如果是其他对象,则对象必须包含 __len__() 方法,否则会产生异常。

>>> a = [1, 2, 3]
>>> len(a)
3
>>> b = 'abcdefg'
>>> len(b)
7
>>> 
>>> class MyTest:
...     def __len__(self):
...         return 5
... 
>>> c = MyTest()
>>> len(c)
5

list([iterable])

  创建并返回一个列表对象。如果没有传入参数,则返回一个空列表。

  传入的参数必须是一个可迭代的,迭代器中的每一个对象将作为列表的一个元素。

>>> list('abcd')
['a', 'b', 'c', 'd']
>>> list([1,2,3])
[1, 2, 3]

locals()

  返回当前命名空间的{对象: 值} 字典。

>>> def foo():
...     i = 1
...     j = 2
...     k = 3
...     print(locals())
... 
>>> foo()
{'i': 1, 'k': 3, 'j': 2}

map(function, iterable, ...)

  返回一个迭代器。迭代器中的每一个对象将是传入的迭代器根据function的映射。

  如果超过两个参数,后面的参数适用于 function 有多个参数的情况,因此后面的迭代器的长度不能小于 iterable

>>> for i in map(lambda x: x**2, [1,2,3]):
...     print(i)
... 
1
4
9
>>> for i in map(lambda x,y: x**y, [2,2,2], [1,2,3]):
...     print(i)
... 
2
4
8

max(iterable [, key, default])  max(arg1, arg2, *args [, key])

  返回最大值。要比较的参数可以是一个可迭代的对象,也可以直接传入对象列表。

  参数 key 可以改变默认的比较方式。

  当传入的是一个迭代器时,如果迭代器为空,则返回default值,如果没有传入default将产生异常。

>>> max([3,5,1,7,9,2])
9
>>> max('aaa', 'bbb', 'ccc')
'ccc'
>>> 
>>> max([(4,2), (3,3), (2,4)], key=lambda x: x[1])
(2, 4)
>>> max([], default='empty')
'empty'

memoryview(obj)

  返回一个内存观察对象。传入的对象必须支持缓冲区协议,内建对象中支持的有 bytesbytearray

  内存观察对象提供一个共享的内存,可以在不需要复制的情况以不同的方式访问共享内存。在大量数据处理时比较有用。

>>> a = memoryview(b'abcdefg')
>>> a
<memory at 0x7f22addc3e88>
>>> a[0]
97
>>> a[1]
98
>>> a.tolist()
[97, 98, 99, 100, 101, 102, 103]
>>> a.tobytes()
b'abcdefg'
>>> a[1:3].tobytes()
b'bc'

min(iterable [, key, default])  min(arg1, arg2, *args [, key])

  返回最小值。用法与 max 类似

>>> min([3,5,1,7,9,2])
1
>>> min('aaa', 'bbb', 'ccc')
'aaa'
>>> min((4,2), (3,3), (2,4), key=lambda x: x[1])
(4, 2)
>>> min([], default='empty')
'empty'

next(iterator [, default])

  返回迭代器中的下一个。一般与 iter() 配合使用。

  当迭代完成以后,如果传入了default参数,则返回default的值,否则产成StopIteration异常

>>> it = iter([1,2,3])
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 
>>> it = iter([1,2,3])
>>> next(it, default='end')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: next() takes no keyword arguments
>>> next(it, 'end')
1
>>> next(it, 'end')
2
>>> next(it, 'end')
3
>>> next(it, 'end')
'end'

object()

  创建一个基本对象。该类是所有类的基类。

>>> a = object()
>>> dir(a)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

oct(x)

  返回x的8进制字符串,字符串以'0o'开头,字符串中的字符都以小写形式表示。

  当x不是一个int型对象时,则对象必须定义一个__index__() 方法,则返回整型值,否则将产生异常。

>>> oct(10)
'0o12'
>>> oct(16)
'0o20'

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

  打开一个文件,返回一个文件的对象。open的使用非常丰富,这里为扫盲,只说明最常用最基本的用法。

  参数 file, 文件名,路径可以为相对,也可以为绝对。

  参数 encoding,以何种编码方式打开文件,例如 'utf-8', 'gbk'等。

  参数 mode,打开模式

    - 'r',  只读方式,如果文件不存在将产生异常。

    - 'w',  写方式打开,如果文件存在,原文件将被覆盖,如果不存在将创建新文件。

    - 'x',创建一个新文件并打开,如果文件存在将产生异常。

    - 'a',  追加方式打开,如果文件存在,打开后指针指向文件尾部,如果不存在将创建新文件。

    - ‘b',  二进制模式打开。

    - 't',  文本模式打开(缺省)

    - '+', 读写方式打开,配合r, w, a使用

    其中常用组合模式,r+, rb+, w+, wb+, a+, ab+

  注: 为保证使用安全性,常配合 with 使用

>>> f = open('test.txt', 'r', encoding='utf-8')
>>> f.readline()
'test line1\n'
>>> f.close()
>>> 
>>> with open('test.txt', 'r') as f:
...     print(f.readline())
... 
test line1

ord(c)

  返回字符的unicode码,该函数是chr()反向操作。

  注: 参数必须是单一的字符

>>> ord('a')
97
>>> ord(chr(99))
99
>>> chr(ord('k'))
'k'

pow(x, y [, z])

  求 xy 次方。结果相当于  x ** y

  如果传入了参数 z,则相当于 (x ** y) % z

  注:  如果 y 是负数,则不能传入 z

>>> pow(2, 3)
8
>>> pow(2, 4, 5)
1

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

  打印函数。可以一次打印多个对象。sep, end, file, flush 如果需要修改,需以关键字形式指定。

  参数sep,多个对象的打印内容之间的分割符。

  参数end,所有对象内容输出完毕后输出的字符。

  参数file, 输出的地方,默认是标准输出,可以修改成文件等具有write() 方法的对象。

  参数flush, 是否立即输出。False 可能会暂时放入缓冲区。

  注: 对于自定义的对象,如果想被print调用需要具有 __str__() 方法

>>> print('hello,world')
hello,world
>>> print('hello', 'world')
hello world
>>> print('hello', 'world', sep='---')
hello---world
>>> print('hello', 'world', end='\n\n\n')
hello world


>>> print('hello', 'world', '123', flush=True)
hello world 123
>>> 
>>> class MyTest:
...     def __str__(self):
...         return 'test'
... 
>>> a = MyTest()
>>> print(a)
test

property(fget=None, fset=None, fdel=None, doc=None)

  属性装饰器。可以方便的访问对象的某个属性,避免直接操作内部属性。

  函数返回一个装饰属性,将关联 fget, fset, fdel 函数

  参数doc提供一个帮助信息。

  当用@property装饰类方法时,方法名将作为装饰属性,方法定义为只读。此时如果需要set和del需要配合@method.setter和@method.deleter使用

  注1: 两种实现方式中,get, set 和 del 都不是必须全部存在的

  注2: 两种实现方式中,get函数都只能有self参数

class MyTest:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, v): 
        self._x = v 

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "The '_x' property")



class MyTest2:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, v): 
        self._x = v 

    @x.deleter
    def x(self):
        del self._x


>>> a = MyTest()
>>> a.x
>>> 
>>> a = MyTest()
>>> print(a.x)
None
>>> a.x = 'test'
>>> print(a.x)
test
>>> del a.x
>>> print(a.x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/taopeng/Workspace/CodeWars/tmp.py", line 7, in getx
    return self._x
AttributeError: 'MyTest' object has no attribute '_x'



>>> b = MyTest2()
>>> print(b.x)
None
>>> b.x = 3
>>> print(b.x)
3
>>> del b.x
>>> print(b.x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/taopeng/Workspace/CodeWars/tmp.py", line 25, in x
    return self._x
AttributeError: 'MyTest2' object has no attribute '_x'

range(stop)  range(start, stop [, step])

  生成一个数字序列迭代器。

  当只有一个参数时,序列为0到stop(不包括stop值), 步进为1

  当有两个参数时,序列为start到stop(不包括stop值),步进为1

  三个参数时,即可自定义步进

>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(3,9))
[3, 4, 5, 6, 7, 8]
>>> list(range(1,10,2))
[1, 3, 5, 7, 9]

repr(object)

  和 ascii() 类似,返回对象的可打印字符串。

  自定义对象如果需要 repr(),需要定义__repr__() 方法

>>> a = 123
>>> repr(a)
'123'
>>> b = 'test'
>>> repr(b)
"'test'"
>>> class MyTest:
...     def __repr__(self):
...         return 'Hello, world'
... 
>>> c = MyTest()
>>> repr(c)
'Hello, world'

reversed(seq)

  返回一个序列逆序的迭代器。

  如果是自定义对象,需要实现 __reversed__() 方法或者支持序列协议

>>> list(reversed([1,2,3,4,5]))
[5, 4, 3, 2, 1]

round(number [, ndigits])

  保留指定的小数位,返回一个最接近的数。

  参数 ndigits 默认为None, 即只保留整数部分。

  注1: 该函数当向上和向下取近似距离相同时,优先取较小的偶数。

  注2: ndigits 如果填0,虽然只保留整数位,但是会返回浮点型

>>> round(1.1)
1
>>> round(1.8)
2
>>> round(1.5)
2
>>> round(2.5)
2
>>> round(3.5)
4
>>> round(3.14, 1)
3.1
>>> round(3.16, 0)
3.0

set([iterable])

  创建一个集合对象。如果没有参数则创建一个空集合。

  参数必须是可迭代的。迭代器中的相同的对象将只会保留一个。

>>> set([1,2,3])
{1, 2, 3}
>>> set([1,1,2,2,3])
{1, 2, 3}
>>> set(range(10))
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

setattr(object, name, value)

  给对像的指定属性赋值。如果对象不存在该属性,将先创建该属性。

  注: 参数 name 是一个字符串

>>> class MyTest():
...     pass
... 
>>> a = MyTest()
>>> setattr(a, 'test', 'hello')
>>> getattr(a, 'test')
'hello'
>>> setattr(a, 'test', 'hello, world')
>>> getattr(a, 'test')
'hello, world'
>>> a.test
'hello, world'

slice(stop)  slice(start, stop [, step])

  生成一个分片对象。用于对序列进行分片。

  当只有一个参数时,序列为0到stop(不包括stop值), 步进为1

  当有两个参数时,序列为start到stop(不包括stop值),步进为1

  三个参数时,即可自定义步进

  不过一般可以直接在序列中用分片语法,例如 a为一个列表,分片语法为: a[start:stop:step]

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

sorted(iterable, *, key=None, reverse=False)

  返回一个经过排序的列表。key, reverse参数必须以关键字形式传入。

  需要排序的对象必须是可迭代的。

  参数key,排序的关键字。

  参数reverse,是否逆序,默认从小到大。

  注: 参数*可以忽略。

>>> a = [5,6,3,1,7,4,9]
>>> sorted(a)
[1, 3, 4, 5, 6, 7, 9]
>>> sorted(a, reverse=True)
[9, 7, 6, 5, 4, 3, 1]
>>> b = ['B', 'a', 'g', 'F', 'z', 'K']
>>> sorted(b)
['B', 'F', 'K', 'a', 'g', 'z']
>>> sorted(b, key=str.lower)
['a', 'B', 'F', 'g', 'K', 'z']

staticmethod(function)

  一般作为函数装饰器使用 @staticmethod 。类似 classmethod

  将类中的一个方法指定为静态方法  

  静态方法的调用可以直接通过类调用,即C.f(); 也可以通过实例调用,即C().f()

  个人感觉静态方法适合将函数归类打包

  注:静态方法是可以继承的

>>> class MyTest:
...     @staticmethod
...     def static_test():
...         print('This is a static method')
... 
>>> 
>>> a = MyTest()
>>> a.static_test()
This is a static method
>>> 
>>> MyTest.static_test()
This is a static method

str(object='')  str(object=b'', encoding='utf-8', errors='strict')

  创建并返回一个字符串对象。

  可以使用指定的对象来初始化。初始化将使用对象的 __str__() 方法返回的值。

>>> str(12345)
'12345'
>>> str('test')
'test'
>>> str([1,2,3])
'[1, 2, 3]'
>>> class MyTest:
...     def __str__(self):
...         return 'Hello'
... 
>>> a = MyTest()
>>> str(a)
'Hello'

sum(iterable [, start])

  对一个序列求和。

  参数start, 指定一个初始值,默认是0

>>> sum(range(5))
10
>>> sum(range(5), 3)
13
>>> sum({1,2,3})
6

super([type [, object-or-type]])

  返回父类的方法、对象。一般用于继承处理中,特别是初始化。

  在初始化中,super的参数可以省略。

class A:
    def __init__(self):
        print('Class A init')

class B(A):
    def __init__(self):
        super().__init__()
        print('Class B init')


class C(A):
    def __init__(self):
        super(C, self).__init__()
        print('Class C init')


>>> b = B()
Class A init
Class B init
>>> c = C()
Class A init
Class C init

tuple([iterable])

  创建并返回一个元组对象。

  可以使用一个可迭代对象初始化元组。

>>> tuple(range(5))
(0, 1, 2, 3, 4)
>>> tuple('test')
('t', 'e', 's', 't')

type(object)  type(name, bases, dict)

  两个功能。传入的参数个数不同,功能不同

  一个参数时,返回对象所属的类。

  三个参数时,动态创建一个自定义类的对象。

  当需要动态创建一个类时,

  参数name, 类名

  参数bases, 类的基类,使用一个元组传入,因此可以有多个父类。

  参数dict, 类的属性和方法字典。{属性名=属性值,方法名=函数名}, 其中“函数名”是一个已经定义的函数

  注: 直接通过字典传入的方法是一个静态方法。

>>> a = [1,2,3]
>>> type(a)
<class 'list'>
>>> 
>>> def test_func():
...     print('This is a test func.')
... 
>>> b = type('MyTest', (object, ), dict(test_attr='Hello', test_method=test_func))
>>> type(b)
<class 'type'>
>>> b.test_attr
'Hello'
>>> b.test_method()
This is a test func.

vars([object])

  返回对象新添加的属性字典。如果没有参数,返回当前命名空间更新的属性字典。

  实际上函数返回的就是对象 __dict__ 属性的值。

  注: 在初始化时添加的属性不会放入 __dict__

>>> class MyTest:
...     def __init__(self):
...         a = 1
...         b = 2
... 
>>> a = MyTest()
>>> 
>>> vars(a)
{}
>>> a.c = 3
>>> vars(a)
{'c': 3}
>>> a.__dict__
{'c': 3}
>>> 
>>> vars()
{'MyTest': <class '__main__.MyTest'>, 'a': <__main__.MyTest object at 0x7f1ca394f828>, '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__'}

zip(*iterables)

  将多个序列进行重新组合,返回一个元组列表。

  每个元组从各个序列中各提取一个值。因此元组的个数由最短的序列决定。

>>> list(zip([1,1,1], [2,2,2], [3,3,3]))
[(1, 2, 3), (1, 2, 3), (1, 2, 3)]
>>> 
>>> list(zip([1,2,3], [4,5,6], [7,8,9]))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> 
>>> list(zip([1,1,1], [2,2,2], [3,3]))
[(1, 2, 3), (1, 2, 3)]

 

转载于:https://www.cnblogs.com/tp1226/p/8446503.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值