《Core Python 2nd》读书摘要一

2024-04-02 07:58
文章标签 python core 读书 摘要 2nd

本文主要是介绍《Core Python 2nd》读书摘要一,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.print语句在2.0版本之后支持重定向,使用>>语法:

输出到标准错误流

import sys
print >> sys.stderr, 'Fatal error: invalid input!'

输出到log文件

logfile = open('/tmp/mylog.txt', 'a')
print >> logfile, 'Fatal error: invalid input!'
logfile.close()
 


2.Python can be considered “call by reference.”注意以下代码的区别

a = 10
b = 10
c = 10.0
d = 10.0

 

a is b   ---> True
c is d   ---> False

因为到出书为止,Python会interns或cache从(-1, 100)的整数,因为它认为它们会经常使用。而float则不会。


3.内置数值举例

int          0101                84                 -237                0x80    017     -680    -0X92
long       29979062458L   -84140l  0xDECADEDEADBEEFBADFEEDDEAL
bool       True                False
float       3.14159         4.2E-10 -90.    6.022e23        -1.609E?19
complex 6.23+1.5j       -1.23-875J      0+1j                9.80665-8.31441J -.0224+0j

其中注意complex在虚部j、J的前面一定要加系数,即使是1。


4.Table 2.1 Useful Built-In Functions for New Python Programmers

Function                Description
dir([obj])               Display attributes of object or the names of global variables if no parameter given
help([obj])            Display object's documentation string in a pretty-printed format or enters interactive help if no parameter given
int(obj)                 Convert object to an integer
len(obj)                Return length of object
open(fn, mode)    Open file fn with mode ('r' = read, 'w' = write)
range([[start,      Return a list of integers that begin at start up to
]stop[,step])       but not including stop in increments of step; start
                    defaults to 0, and step defaults to 1
raw_input(str)     Wait for text input from the user, optional prompt string can be provided
str(obj)                Convert object to a string
type(obj)             Return type of object (a type object itself !)


5.多变量赋值时建议使用Tuple

 (x,y,z) = (1,2,'Python')


6.Python Keywords

and         as             assert      break
class       continue    def          del
elif          else           except     exec
finally      for             from        global
if             import       in             is
lambda   not            or            pass
print       raise         return      try
while      with          yield        None


7.Here is a summary of the special underscore usage in Python:

 _xxx          Do not import with 'from module import *',在Python中_xxx被看做Private
 __xxx__    System-de?ned name,在Python中__xxx__被看做特殊用途
 __xxx        Request private name mangling in classes
因此作者不建议使用underscore作为变量的开始


8.一个module内常用的布局
# (1) startup line (Unix)
# (2) module documentation  (module.__doc__)
# (3) module imports             (import os)
# (4) variable declarations
# (5) class declarations
# (6) function declarations
# (7) "main" body                  (unindented highest level statement)


9.所有模块中的highest level语句都将被执行,无论是被import还是在command line,等等。因此应该将所有不想被直接调用的语句都写成function或class。
如何判定一个模块是被import的还是直接执行的,可以用__name__关键字
 __name__ contains module name if imported
 __name__ contains ’__main__’ if executed directly

因此在一个模块中可以在"main"部分加上测试:


10.对often-used或name-lengthy的模块属性用别名的方式(也可以看做局部引用),可以加快编译器的look up速度
因为Python使用的是引用机制,如ls = os.linesep


11. The type type object is also the mother of all types and is the default metaclass for all standard Python classes.
如:>>> type(42)            会得到<type 'int'>
而  >>> type(type(42))   会返回 <type 'type'>
Classes are now types, and instances are now objects of their respective types.
    >>> type(None)          得到 <type 'NoneType'>


12.所有的内置类型都会有一个True和False以供测试:
为False的有: 空集合、None、布尔False、任何数学形式零
为True的有:  不为False的
User-created class instances have a false value when their nonzero (__nonzero__()) or length (__len__()) special methods, if defined, return a zero value.


13.标准Types:  Integer、Boolean、Long integer、Floating point real number、Complex number、String、List、Tuple、Dictionary
其它内置Types: Type、Null object(None)、File、Set/Frozenset、Function/Method、Module、Class
Internal Types:Code、Frame、Traceback、Slice、Ellipsis、Xrange


14.多重比较

 >>> 3 < 4 < 7   # same as ( 3 < 4 ) and ( 4 < 7 )
    True
>>> 4 > 3 == 3  # same as ( 4 > 3 ) and ( 3 == 3 )
    True
>>> 4 < 3 < 5 != 2 < 7
    False


15. a is b      is an equivalent expression to id(a) == id(b)
    a is not b  is an equivalent expression to id(a) != id(b)


16.标准内置函数:
cmp(obj1, obj2)、repr(obj) or ‘obj‘、str(obj)、type(obj)


17.The executive summary is that repr() is Python-friendly while str() produces human-friendly output.


18.Python不支持函数和方法的重载,因为它的参数就没有类型这一说,因此不用重载也可以实现这一效果:

You could also try a variable-length argument list, e.g.


19.用type和isinstance来检测数值类型的一个示例:


20.Type Factory Functions

其中一部分Factory Function是由以前的BIF(Build-in Function)演变而来

int(), long(), float(), complex(), str(), unicode(), basestring(), list(), tuple(), type()

另一部分是新增的new-style类的Factory Function

• dict()• bool()• set()• frozenset()• object()• classmethod()• staticmethod()• super()• property()• file()

这篇关于《Core Python 2nd》读书摘要一的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/869413

相关文章

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

Python包管理工具pip的升级指南

《Python包管理工具pip的升级指南》本文全面探讨Python包管理工具pip的升级策略,从基础升级方法到高级技巧,涵盖不同操作系统环境下的最佳实践,我们将深入分析pip的工作原理,介绍多种升级方... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核