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. ...
随机推荐
- Flask框架:运用Ajax轮询动态绘图
Ajax是异步JavaScript和XML可用于前后端交互,在之前<Flask 框架:运用Ajax实现数据交互>简单实现了前后端交互,本章将通过Ajax轮询获取后端的数据,前台使用echa ...
- 【深入浅出 Yarn 架构与实现】1-2 搭建 Hadoop 源码阅读环境
本文将介绍如何使用 idea 搭建 Hadoop 源码阅读环境.(默认已安装好 Java.Maven 环境) 一.搭建源码阅读环境 一)idea 导入 hadoop 工程 从 github 上拉取代码 ...
- MindSpore Graph Learning
技术背景 MindSpore Graph Learning是一个基于MindSpore的高效易用的图学习框架.得益于MindSpore的图算融合能力,MindSpore Graph Learning能 ...
- 查看服务器出口ip
[root@iZap201hv2fcgry1alvbznZ ~]# curl cip.cc IP : xxx.xxx.xx.xx 地址 : 中国 浙江 绍兴 运营商 : 移动 数据二 : 浙江省绍兴市 ...
- mysql忽略大小写配置
#更改配置文件:vim /etc/my.cnf#添加此行在[mysqld]下lower_case_table_names=1#重启服务systemctl restart mysqld
- 基于python的数学建模---scipy库
instance1: 求解下列线性规划问题 s.t. 代码: from scipy import optimizeimport numpy as npc = np.array([2,3,-5])A ...
- Bugku md5 collision
题目名字都叫md5碰撞,那就肯定和md5碰撞脱不了关系了 打开题目,首先让我们输入a 行吧,随意post一个a=1进去 结果提示flase 这里应该是有特殊值,我们找找看 查看源码,抓包 没找到 试试 ...
- 【消息队列面试】15-17:高性能和高吞吐、pull和push、各种MQ的区别
十五.kafka高性能.高吞吐的原因 1.应用 日志收集(高频率.数据量大) 2.如何保证 (1)磁盘的顺序读写-pagecache关联 rabbitmq基于内存读写,而kafka基于磁盘读写,但却拥 ...
- 使用Java刷评论为平台引流的经历
场景:需要在一网站中批量评论留言. 分析接口: 列表接口获取idList,返回的是json数据直接用FastJson转就可以,如果返回的是HTML片段,则需要使用Jsoup进行提取,值得一学,常用于爬 ...
- Burp Suite
Burp Suite proxy代理 1.首先在浏览器中设置代理配置 火狐浏览器先点击右上角三个杠--选项--常规--网络设置 2.打开Burp Suite进行抓包 Proxy代理--options中 ...