《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中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

一文教你Python如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

基于Python打造一个智能单词管理神器

《基于Python打造一个智能单词管理神器》这篇文章主要为大家详细介绍了如何使用Python打造一个智能单词管理神器,从查询到导出的一站式解决,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 项目概述:为什么需要这个工具2. 环境搭建与快速入门2.1 环境要求2.2 首次运行配置3. 核心功能使用指

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息