Python内置对象(一)
Python内置对象(一)
分多次讲解
这部分相对比较简单,偶尔一些特殊的做法会强调下(前面加★)
总览
builtins = [_ for _ in dir(__builtins__) if not _[0].isupper() and _[0] != '_']
print('一共有{}个内置对象'.format(len(builtins))) # 73
print(builtins)
['abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
- 这73个个内置对象很多是非常简单的,但有些非常有用、常用,知道他们是必须的,并运用到我们的编程中会让一些事情变得简单
- 很多的资料会跟你说这是内置函数,但其实有的不是函数,是类,所以叫对象似乎更合适
分类
类别 | 函数|类 | 作用 |
---|---|---|
数学 | abs | 求绝对值 |
divmod | 求商和余数 | |
max | 最大 | |
min | 最小 | |
pow | 求幂 | |
round | 保留几位小数 | |
sum | 求和 | |
进制 | bin | 二进制 |
hex | 十六进制 | |
oct | 八进制 | |
类型 | bool | 求布尔 |
bytes | 转换成字节类型 | |
complex | 复数 | |
dict | 转换为dict | |
float | 转换为float | |
frozenset | 冻结集合 | |
int | 转换为int | |
list | 转换为list | |
set | 转换为set | |
str | 转换为str | |
tuple | 转换为tuple | |
迭代器 | iter | 迭代 |
enumerate | 枚举 | |
next | 下一个 | |
range | 范围 | |
reversed | 逆向迭代器 | |
转换 | chr | 转换得到字符unicode |
classmethod | 转换为类方法 | |
staticmethod | 转换为静态方法 | |
ord | 跟chr的反操作 | |
对象 | callable | 检查一个对象是否是可调用的 |
delattr | 删除属性 | |
getattr | 获取属性 | |
setattr | 设置属性 | |
dir | 查看对象属性方法 | |
isinstance | 是否是对象实例 | |
issubclass | 是否为子类 | |
super | 父类 | |
type | 查看对象类型 | |
vars | 返回对象信息 | |
函数式编程 | filter | 过滤 |
map | 映射 | |
sorted | 排序 | |
输入输出 | 输出 | |
input | 输入 | |
其他 | all | 都为真才为真 |
any | 一个为真就为真 | |
ascii | ascii转换 | |
format | 格式化 | |
id | 返回对象标识 | |
len | 求容器长度 | |
help | 获取帮助 | |
globals | 当前的全局变量 | |
hash | 返回该对象的哈希值 | |
eval | 计算 | |
exec | 执行 | |
repr | 返回对象的str格式 | |
open | 打开文件 | |
property | 属性 | |
zip | 压缩 | |
冷门 | exit | 退出 |
locals | 以字典类型返回当前位置的全部局部变量 | |
memoryview | 返回给定参数的内存查看对象 | |
object | 无属性的根类 | |
breakpoint | 调试相关,断点 | |
bytearray | 字节数组 | |
compile | 编译成代码或 AST 对象 | |
copyright | ??? | |
credits | ??? | |
license | ??? | |
quit | 退出 | |
slice | 切片 |
一、 数学
abs 绝对值
abs(x, /)
Return the absolute value of the argument.
- 这是最简单的,也没啥变化
abs(-1) # 1
- 如果你不知道/的意思,你可以参考我写的另外一篇文档Python中的函数定义中的斜杠/和星号*
>>> abs(x=-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: abs() takes no keyword arguments
divmod 商和余数
divmod(x, y, /)
Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
- 返回的是一个tuple,商x//y,余数x%y
b = 7
c = 3
div,mod = divmod(b,c)
print('商是',div,f'也就是{b}//{c}',)
print('余数是',mod,f'也就是{b}%{c}')
★max 最大
max(...)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
- max是相对高级一点的函数,平常我们用的都比较简单
max(1,2) # 2
max(1,2,3) # 3
max([1,2,3,4]) # 4 # 本质上,这3种都是iterable,前2个传递的是元组,也可以是列表等容器
names = 'wuxianfeng','qianhanyi','qianyuli'
max(names) # 得到的是wuxianfeng,首字符的ascii,如果一样依次比较下去
- 排序的依据key,你可以参考我写的另外一篇文章Python函数式编程之map/filter/reduce/sorted
names = 'wuxianfeng','qianhanyi','qianyuli','helloworld!!!'
max(names,key=len) # 这个key就是排序的依据 # 得到的是长度最长的
nums = [123,45,6789,-12345]
max(nums,key=abs) # 求离原点最远的数
nums = [[10,2],[20,3],[40,5],[30,4]]
max(nums,key=lambda x:x[1]) # [40,5] # 如果是一个坐标x,y,那就是y坐标最大的数
min(nums,key=lambda x:x[1]) # [10,2] # min就不讲了,跟max是一样的
min 最小
min(...)
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its smallest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the smallest argument.
- 参考max的做法即可
pow 幂
pow(base, exp, mod=None)
Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.
- pow求幂,只不过我们一般就用2个参数的调用方式,3个参数基本不用,求幂后取余
pow(2,3) # 2的3次方 8
pow(2,3,3) # 8 % 3 余2 ==>2
pow(2,3,4) # 8 % 4 没有余数 ==> 0
round 精度
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.
- 冷门的,很少用吧
round(3.1415,2) # 3.14
round(3.1415,3) # 3.142
round(999993.1415,-3) # 1000_000.0
round(999793.1415,-2) # 999800.0
sum 求和
sum(iterable, /, start=0)
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
- 典型的误区
sum(1,2,3)
TypeError Traceback (most recent call last)
<ipython-input-35-dd9496db4b54> in <module>
----> 1 sum(1,2,3)
TypeError: sum() takes at most 2 arguments (3 given)
- 常规的做法
sum([1,2,3]) # 6
sum((1,2,3)) # 6
- start参数
sum([1,2,3],start=2) # 8 = 6+2
二、进制
这部分没有高级用法,也非常简单,看example就行了
bin 二进制
bin(number, /)
Return the binary representation of an integer.
>>> bin(2796202)
'0b1010101010101010101010'
- 唯一你要注意的是返回的类型是个str
type(bin(10)) # str
oct 八进制
oct(number, /)
Return the octal representation of an integer.
>>> oct(342391)
'0o1234567'
hex 十六进制
hex(number, /)
Return the hexadecimal representation of an integer.
>>> hex(12648430)
'0xc0ffee'
三、类型
这个分类下的都跟类型有关系
bool 布尔
class bool(int)
| bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.
|
| Method resolution order:
| bool
| int
| object
|
| Methods defined here:
|
| __and__(self, value, /)
| Return self&value.
|
| __or__(self, value, /)
| Return self|value.
|....(还有很多魔术方法)
- 首先这是一个类,但它是小写的
- 继承自int类型: class bool(int),它不能被继承(怎么做到的?)
- True和False是唯一的2个实例
bool(1) # True
bool(0) # False
bool('a') #True
bool([]) # False # 写到这里你会发现就是if 条件后面的东西
bool([0,0,0]) # True
issubclass(bool,int) # True
bytes 字节
class bytes(object)
| bytes(iterable_of_ints) -> bytes
| bytes(string, encoding[, errors]) -> bytes
| bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
| bytes(int) -> bytes object of size given by the parameter initialized with null bytes
| bytes() -> empty bytes object
|
| Construct an immutable array of bytes from:
| - an iterable yielding integers in range(256)
| - a text string encoded using the specified encoding
| - any object implementing the buffer API.
| - an integer
这是一个相对复杂的类
bytes() 返回一个空的bytes对象
bytes(数字) 这个数字就是大小(长度),每个初始化为\x00
bytes(5) # b'\x00\x00\x00\x00\x00'
bytes(bytes_or_buffer),这个不知道咋用(没用过)
bytes(iterable_of_ints)
bytes([1,2,3,4]) # b'\x01\x02\x03\x04'
用的最多的是这种,bytes里面塞一个str,并指定encoding,作用是将字符串转换为字节序列
# 一定要给出encoding参数
bytes('hello') TypeError Traceback (most recent call last)
<ipython-input-16-34da9840e7ee> in <module>
----> 1 bytes('hello') TypeError: string argument without an encoding
bytes('hello','utf-8') # b'hello' bytes('中国','gbk') #b'\xd6\xd0\xb9\xfa' bytes('中国','utf-8') # b'\xe4\xb8\xad\xe5\x9b\xbd'
complex 复数
class complex(object)
| complex(real=0, imag=0)
|
| Create a complex number from a real part and an optional imaginary part.
|
| This is equivalent to (real + imag*1j) where imag defaults to 0.
|
| Methods defined here:
|
- 数学中的复数,实部real,虚部imag默认为0,没啥好说的,基本用不到
a = 1+3j
type(a) #complex
complex(2,3) # 2+3j
★dict 字典
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
dict这个内置方法的用法是很多同学一开始的时候会忽略的
dict() 返回一个空字典,类型的这些内置函数(类)多数支持这个方法
dict(mapping)
dict(zip(['a','b'],(1,2))) # {'a': 1, 'b': 2} # 这里要用到一个zip的做法,zip是非常值得深入学习的一个内置函数
dict(iterable)
dict([('a',1),('b',2)]) # {'a': 1, 'b': 2}
dict(**kwargs)
dict(a=1,b=2) # {'a': 1, 'b': 2}
float 浮点
class float(object)
| float(x=0, /)
|
| Convert a string or number to a floating point number, if possible.
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
这个用起来比较简单
float('2') # 2.0 float(1) # 1.0
frozenset 冻结集合
class frozenset(object)
| frozenset() -> empty frozenset object
| frozenset(iterable) -> frozenset object
|
| Build an immutable unordered collection of unique elements.
|
| Methods defined here:
|
| __and__(self, value, /)
| Return self&value.
冻结的集合,不可修改,看这个的方法,跟普通的set的区别
fz = frozenset([1,1,3,2,3]) # {1,2,3}
[_ for _ in dir(fz) if _[0]!='_'] # ['copy','difference','intersection','isdisjoint','issubset','issuperset','symmetric_difference','union']
[_ for _ in dir(set) if _[0]!='_']
# ['add','clear','copy','difference','difference_update','discard','intersection','intersection_update','isdisjoint','issubset','issuperset','pop','remove','symmetric_difference','symmetric_difference_update','union','update']
★int 整形
class int(object)
| int([x]) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
|
这个类是在做进制转换的时候非常有用
int('10') # 得到 10
int('10',2) # 得到2 , 10在二进制中就是2
int('11',2) # 3 int('ff',16) # 255
int('FF',16) # 255 不会区分大小写 int('12',3) # 3进制中12表示5 , 还可以这些乱七八糟的进制表示
int('0b100',base=0) # 如果是base是0,就自己从前面的str中解析得到是个什么进制的数
int('0b100',0)
list 列表
class list(object)
| list(iterable=(), /)
|
| Built-in mutable sequence.
|
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
这个你可能是用的非常多的,没啥好说的
list() # 空的list list(1,2,3) # 别这样,错了 list({1,2,3})
list((1,2,3))
list(range(5)) # 可迭代的即可
set 集合
class set(object)
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
set()得到一个空集合
set(可迭代对象)可以得到一个新的集合对象
set([1,2,3,1,2]) # {1,2,3} set() # {} 空的set set({'a':1,'b':2}) # {'a','b'}
str 字符串
class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
可以返回对象的repr或者__str__
class P:
def __repr__(self):
return 'ppppp' p1 = P()
print(str(p1)) # 你不加str也是一样的
最简单的用法
str(1) # '1' str({'a':1}) # "{'a': 1}"
tuple 元组
class tuple(object)
| tuple(iterable=(), /)
|
| Built-in immutable sequence.
|
| If no argument is given, the constructor returns an empty tuple.
| If iterable is specified the tuple is initialized from iterable's items.
|
| If the argument is a tuple, the return value is the same object.
|
| Built-in subclasses:
| asyncgen_hooks
| UnraisableHookArgs
- tuple() 返回一个空的元组
- tuple(可迭代对象)返回一个不可变的序列
Python内置对象(一)的更多相关文章
- 浅谈Python内置对象类型——数字篇(附py2和py3的区别之一)
Python是一门面向对象的编程设计语言,程序中每一样东西都可以视为一个对象.Python内置对象可以分为简单类型和容器类型,简单类型主要是数值型数据,而容器类型是可以包含其他对象类型的集体,如序列. ...
- python——内置对象
python的内置对象 对象类型 常量示例/用法 Number(数字) 3.14159, 1234, 999L 3+4j String(字符串) 'spam', "guido's" ...
- Python内置函数(15)——memoryview
英文文档: class memoryview(obj) memoryview objects allow Python code to access the internal data of an o ...
- Python内置函数(42)——memoryview
英文文档: class memoryview(obj) memoryview objects allow Python code to access the internal data of an o ...
- Python 内置函数 memoryview
转载自:https://www.cnblogs.com/sesshoumaru/p/6035548.html 英文文档: class memoryview(obj) memoryview object ...
- Python面向对象——内置对象的功能扩展
1.扩展Python内置类 Python的数据类型 列表(list).字典(dict).集合(set).文件(file).字符串(str),这些都是对象 扩展list的功能,详解如图: 我们给列表添加 ...
- [转]python file文件操作--内置对象open
python file文件操作--内置对象open 说明: 1. 函数功能打开一个文件,返回一个文件读写对象,然后可以对文件进行相应读写操作. 2. file参数表示的需要打开文件的相对路径(当前 ...
- python 之 前端开发( JavaScript变量、数据类型、内置对象、运算符、流程控制、函数)
11.4 JavaScript 11.41 变量 1.声明变量的语法 // 1. 先声明后定义 var name; // 声明变量时无需指定类型,变量name可以接受任意类型 name= " ...
- Python常用内置对象
1.在python中处理的一切都是对象. 2.内置对象可直接使用,如数字.字符串.列表.del等. 3.非内置对象需要导入模块才能使用,如正弦函数sin(x),随机数产生函数random()等.
- python 全栈开发,Day51(常用内置对象,函数,伪数组 arguments,关于DOM的事件操作,DOM介绍)
昨日内容回顾 1.三种引入方式 1.行内js <div onclick = 'add(3,4)'></div> //声明一个函数 function add(a,b){ } 2. ...
随机推荐
- jquery datatable 粗犷
需要学习: HTML.CSS.Javascript Bootstrap: 基于以上三个的一个框架 jQuery:一个 JavaScript 库. jQuery 极大地简化了 JavaScript 编程 ...
- AR Engine光照估计能力,让虚拟物体在现实世界更具真实感
AR是一项现实增强技术,即在视觉层面上实现虚拟物体和现实世界的深度融合,打造沉浸式AR交互体验.而想要增强虚拟物体与现实世界的融合效果,光照估计则是关键能力之一. 人们所看到的世界外观,都是由光和物质 ...
- Linux配置篇 - Vmware网络配置
网络配置 VM 网络详解 vmware提供了三种网络工作模式,Bridged(桥接模式).NAT(网络地址转换模式).Host-Only(仅主机模式): vmware网络配置步骤:编辑 -> 虚 ...
- c++题目:数迷
c++题目:数迷 题目 [题目描述] 给出含有N×N个格子的正方形表格,要求每个格子都填上一个个位数(范围1-N),使得每行.每列以及同一斜线上的数字都不同.部分格子已经填好数字.求满足题意的方案数. ...
- warning: ‘setAxisX‘ is deprecated
解决 将 chart->setAxisX(valueAxisX,lineSeries); 改为: chart->addSeries(lineSeries); chart->creat ...
- 【大数据面试】【框架】Zookeeper作用、半数机制、命令、安装台数
〇.作用 存储和管理数据 Zookeeper=文件系统+通知机制 树形结构,每个节点被称为一个Znode(1MB) 一.半数机制 1.注意 安装奇数台(4台) 二.常用命令 ls get create ...
- Elasticsearch提示low disk watermark [85%] exceeded on [UTyrLH40Q9uIzHzX-yMFXg][Sonofelice][/Users/baid...
mac本地启动es之后发现运行一段时间一分钟就能打印好几条info日志: [2018-03-13T10:15:42,497][INFO ][o.e.c.r.a.DiskThresholdMonitor ...
- django中如何开启事务
一:django中如何开启事务 1.事务的四大特征 ACID A: 原子性 每个事务都是不可分割的最小单位(同一个事物内的多个操作要么同时成功要么同时失败) C: 一致性 事物必须是使数据库从一个一致 ...
- jmeter 之 JSON 断言
1.JSON 断言所在位置:断言->JSON 断言 2.JSON断言中的字段解析 Assert JSON Path exists:json 表达式,判断所字段是否存在,存在则为True, 否则为 ...
- 6、SQL模糊查询LIKE concat用法
concat用来拼接查询的字符串: SELECT * FROM `page_demo` WHERE name LIKE concat('%',#{name},'%') 模糊查询: 1.%代表零个或多个 ...