笔记-python-build-in-types

注:文档内容来源为Python 3.6.5 documentation

1.      built-in types

1.1.    真值测试

所有对象都能够被测试是否为真。

对象默认为真,除非它定义了__bool__()并返回False或者定义了__len__()并返回0

class a():

def __init__(self):

pass

def __bool__(self):

return False

c = a()

if c:

print(True)

其它为假的情况:

  1. None and False
  2. 数字为0,包括0,0.0,0j等
  3. 为空,包括[],(){},’’等

1.2.    boolean operations-and,or,not

  1. 操作返回的是操作数而不是boolean
  2. and返回第一个为假的操作数或最后一个值
  3. or返回第一个为真的操作数或最后一个值

1.3.    comparisons

<, <=, >, >=, ==, !=, is, is not

in and not in ,are supported only by sequence types.

1.4.    numeric types-int, float, complex

Operation

Result

Full documentation

x + y

sum of x and y

x - y

difference of x and y

x * y

product of x and y

x / y

quotient of x and y

x // y

floored quotient of x and y

x % y

remainder of x / y

-x

x negated

+x

x unchanged

abs(x)

absolute value or magnitude of x

abs()

int(x)

x converted to integer

int()

float(x)

x converted to floating point

float()

complex(re, im)

a complex number with real part re, imaginary part im. im defaults to zero.

complex()

c.conjugate()

conjugate of the complex number c

divmod(x, y)

the pair (x // y, x % y)

divmod()

pow(x, y)

x to the power y

pow()

x ** y

x to the power y

1.4.1.   bitwise operations on integer types

Operation

Result

Notes

x | y

bitwise or of x and y

x ^ y

bitwise exclusive or of x and y

x & y

bitwise and of x and y

x << n

x shifted left by n bits

(1)(2)

x >> n

x shifted right by n bits

(1)(3)

~x

the bits of x inverted

1.5.    iterator types

iterator.__iter__()

Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and instatements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.

iterator.__next__()

Return the next item from the container. If there are no further items, raise the StopIteration exception. This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.

1.6.    sequence types-list, tuple,range

1.6.1.   common sequence operations

Operation

Result

x in s

True if an item of s is equal to x, else False

x not in s

False if an item of s is equal to x, else True

s + t

the concatenation of s and t

s * n or n * s

equivalent to adding s to itself n times

s[i]

ith item of s, origin 0

s[i:j]

slice of s from i to j

s[i:j:k]

slice of s from i to j with step k

len(s)

length of s

min(s)

smallest item of s

max(s)

largest item of s

s.index(x[, i[, j]])

index of the first occurrence of x in s (at or after index i and before index j)

s.count(x)

total number of occurrences of x in s

Operation

Result

Notes

s[i] = x

item i of s is replaced by x

s[i:j] = t

slice of s from i to j is replaced by the contents of the iterable t

del s[i:j]

same as s[i:j] = []

s[i:j:k] = t

the elements of s[i:j:k] are replaced by those of t

(1)

del s[i:j:k]

removes the elements of s[i:j:k] from the list

s.append(x)

appends x to the end of the sequence (same ass[len(s):len(s)] = [x])

s.clear()

removes all items from s (same as del s[:])

(5)

s.copy()

creates a shallow copy of s (same as s[:])

(5)

s.extend(t) or s += t

extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t)

s *= n

updates s with its contents repeated n times

(6)

s.insert(i, x)

inserts x into s at the index given by i (same as s[i:i] = [x])

s.pop([i])

retrieves the item at i and also removes it from s

(2)

s.remove(x)

remove the first item from s where s[i] == x

(3)

s.reverse()

reverses the items of s in place

 

1.7.    text sequence type-str

Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points. String literals are written in a variety of ways:

Single quotes: 'allows embedded "double" quotes'

Double quotes: "allows embedded 'single' quotes".

Triple quoted: '''Three single quotes''', """Three double quotes"""

Triple quoted strings may span multiple lines - all associated whitespace will be in

1.7.1.   string methods

  1. str.capitalize() 首字母大写
  2. str.casefold() 大写转换为小写
  3. str.center(width[, fillchar])

return centered in a string of length width.

  1. str.count(sub[, start, end])

return the number of non-overlapping occurrences of substring sub in the range[start, end].

  1. str.encode(encoding=’utf-8’, errors=”strict”)
  2. str.endswith(suffix[, start, end])
  3. str.expandtabs(tabsize=8)

Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size.

  1. str.find(sub[, start, end])
  2. str.format(*args, **kwargs)
  3. str.index(sub[, start, end])

like find(), but raise ValueError when the substring is not found.

  1. str.isalnum()

return true if all characters in the string are alphanumeric and there is at least one character.

  1. str.isdecimal()
  2. str.isdigit()
  3. str.isidentifier()
  4. str.islower()
  5. str.isnumeric()
  6. str.isprintable()
  7. str.isspace()
  8. str.istitle()
  9. str.isupper()
  10. str.join(iterable)

return a string which is the concatention of the strings in iterable.

  1. str.ljust(width[,fillchar])

return the string left justified in a string of length width.

  1. str.lower()
  2. str.lstrip([chars])
  3. static str.maketrans(x[, y, z])
  4. str.partition(sep)
  5. str.replace(old, new[,count])
  6. str.rfind(sub[, start, end])
  7. str.rindex(sub[, start, end])
  8. str.rjust(width[, fillchar])
  9. str.rpartition(sep)
  10. str.rsplit(sep=None, maxsplit=-1)
  11. str.rstrip([chars])
  12. str.split(sep=None, maxsplit=-1)
  13. str.splitlines([keepends])
  14. str.startswith(prefix[, start, end])
  15. str.strip([chars])
  16. str.swapcase()
  17. str.title()
  18. str.translate(table)
  19. str.upper()
  20. str.zfill(width)

return a copy of the string left filled with ASCII ‘0’ digits to make a string of length width.

1.8.    binary sequence types-bytes, bytearray, memoryview

1.8.1.   bytes objects

class bytes(source, encoding, errors)

classmethod fromhex(string)

This bytes class method returns a bytes object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored.

>>>

>>> bytes.fromhex('2Ef0 F1f2  ')

b'.\xf0\xf1\xf2'

hex()

return a string object containing two hexadecimal digits for each byte in the instance.

>>> b'\xf0\xf1\xf2'.hex()

'f0f1f2'

1.8.2.   bytearray objects

class bytearray(source, encoding, errors)

Creating an empty instance: bytearray()

Creating a zero-filled instance with a given length: bytearray(10)

From an iterable of integers: bytearray(range(20))

Copying existing binary data via the buffer protocol: bytearray(b'Hi!')

1.8.3.   bytes and bytearray operations

操作基本与string类似。

1.8.4.   memory views

class memoryview(obj)

code:

v = memoryview(b’abcefg’)

v[1] #98

对于memory views 的好处官方解释是memoryview objects allow Python code to access the internal data of an object that supports the buffer protocol without copying

目前可以理解的好处就是可以减少内存消耗。

注:支持buffer protocol的内建类型有bytes and bytearray。

1.9.    set types-set, frozenset

a set object is an unordered collection of distinct hashable objects.

There are currently two built-in set types, set and frozenset. The set type is mutable — the contents can be changed using methods like add() and remove(). Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. The frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.

  1. calss set([iterable])
  2. class frozenset([iterable])
  3. len(s)
  4. x in s
  5. isdisjont(other)

return true if the set has no elements in common with other

  1. issubset(other)
  2. set <= other

test whether every element in the set is in other.

  1. set < other
  2. issuperset(other)
  3. set >= other
  4. set > other
  5. union(*others)
  6. set |other

return a new set with elements from the set and all others.

  1. set & other
  2. difference(*others)
  3. set – other
  4. symmetric_difference(other)
  5. set ^ other
  6. copy()

return a new set with a shalloww copy of s.

The following table lists operations available for set that do not apply to immutable instaces of frozenset.

  1. update(*others)
  2. set |= other
  3. intersection_update(*others)
  4. set &= other
  5. difference_update(*others)
  6. set -= other
  7. add(elem)
  8. remove(elem)
  9. discard(elem)
  10. pop()
  11. clear()

1.10.        mapping types- dict

1.11.        context manager types上下文管理器with

Python’s “with” statement supports the concept of a runtime context defined by a context manager. This is implemented using a pair of methods that allow user-defined classes to define a runtime context that is entered before the statement body is executed and exited when the statement ends:

contextmanager.__enter__()

Enter the runtime context and return either this object or another object related to the runtime context. The value returned by this method is bound to the identifier in the as clause of with statements using this context manager.

An example of a context manager that returns itself is a file object. File objects return themselves from __enter__() to allow open() to be used as the context expression in a with statement.

An example of a context manager that returns a related object is the one returned by decimal.localcontext(). These managers set the active decimal context to a copy of the original decimal context and then return the copy. This allows changes to be made to the current decimal context in the body of the with statement without affecting code outside the withstatement.

contextmanager.__exit__(exc_type, exc_val, exc_tb)

Exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed. If an exception occurred while executing the body of the with statement, the arguments contain the exception type, value and traceback information. Otherwise, all three arguments are None.

Returning a true value from this method will cause the with statement to suppress the exception and continue execution with the statement immediately following the with statement. Otherwise the exception continues propagating after this method has finished executing. Exceptions that occur during execution of this method will replace any exception that occurred in the body of the with statement.

The exception passed in should never be reraised explicitly - instead, this method should return a false value to indicate that the method completed successfully and does not want to suppress the raised exception. This allows context management code to easily detect whether or not an __exit__() method has actually failed.

1.12.        other built-in types

1.12.1.  modules

1.12.2.  functions

function objects are created by function definitions.The only operation on a function is to call it:func(argument-list).

1.12.3.  methods

methods are functions that are called using the attribute notation.There are two flavors:built-in methods(such as append() on lists) and class instance methods.

笔记-python-build-in-types的更多相关文章

  1. chr()、unichr()和ord(),全半角转换,ValueError: unichr() arg not in range() (wide Python build)

    chr().unichr()和ord() chr()函数用一个范围在range(256)内的(就是0-255)整数作参数,返回一个对应的字符. unichr()跟它一样,只不过返回的是 Unicode ...

  2. waf python build 工具使用流程

    waf python build 工具使用流程 waf 的 build 理念 build 了之后,可以跟踪到 ${SRC} 和 ${TGT} 有关联的文件,只有 ${SRC} 被修改过,在下次buil ...

  3. 笔记-python操作mysql

    笔记-python操作mysql 1.      开始 1.1.    环境准备-mysql create database db_python; use db_python; create tabl ...

  4. 笔记-python异常信息输出

    笔记-python异常信息输出 1.      异常信息输出 python异常捕获使用try-except-else-finally语句: 在except 语句中可以使用except as e,然后通 ...

  5. 笔记-python -asynio

    笔记-python -asynio 1.      简介 asyncio是做什么的? asyncio is a library to write concurrent code using the a ...

  6. 笔记-python lib-pymongo

    笔记-python lib-pymongo 1.      开始 pymongo是python版的连接库,最新版为3.7.2. 文档地址:https://pypi.org/project/pymong ...

  7. 笔记-python tutorial-9.classes

    笔记-python tutorial-9.classes 1.      Classes 1.1.    scopes and namespaces namespace: A namespace is ...

  8. MongoDB学习笔记:Python 操作MongoDB

    MongoDB学习笔记:Python 操作MongoDB   Pymongo 安装 安装pymongopip install pymongoPyMongo是驱动程序,使python程序能够使用Mong ...

  9. 机器学习实战笔记(Python实现)-08-线性回归

    --------------------------------------------------------------------------------------- 本系列文章为<机器 ...

  10. 机器学习实战笔记(Python实现)-05-支持向量机(SVM)

    --------------------------------------------------------------------------------------- 本系列文章为<机器 ...

随机推荐

  1. c#读取word内容,c#提取word内容

    Post by 54admin, 2009-5-8, Views:575 1: 对项目添加引用,Microsoft Word 11.0 Object Library 2: 在程序中添加 using W ...

  2. 编译64位geos库的经验总结

    作者:朱金灿 来源:http://blog.csdn.net/clever101 使用CMake生成Win64的解决方案后,使用VS2010打开这个解决方案,然后 在"C/C++" ...

  3. 画报表框架——Echarts.js

    官网:http://echarts.baidu.com/index.html ————————————————————————————————— 先看看我做的第一个柱状图形报表 ——————————— ...

  4. C++编写双向链表

    创建双向链表类,该类有默认构造函数.类的拷贝函数.类的.实现链表添加数据.升序排序.查找链表中某个节点及删除链表中某个节点的操作 代码实现: #include<iostream> #inc ...

  5. 使用CSS设置Chrome打印背景色

    以下内容适用于Chrome浏览器 打印背景色可以通过在打印预览页面勾选背景图形实现 如果需要在用户不勾选的情况下依然能够打印背景色,可以通过css实现,如,table隔行设置背景色: .data-ta ...

  6. ASP.NET中 前后台方法的相互调用

    后台调用前台js方法: this.Page.ClientScript.RegisterStartupScript(this.GetType(), "js", "ShowM ...

  7. linux下配置Nginx,支持thinkphp

    前言引入 一个刚入行的朋友,刚换工作,入职了一个新公司.新公司一个php开发,就是他.俨然老板把他当成公司扛把子了,把服务器都给了他,让他部署整个php的开发环境.那个朋友是wamp爱好者.然后面对l ...

  8. POJ 2429 GCD & LCM Inverse(Miller-Rabbin素性测试,Pollard rho质因子分解)

    x = lcm/gcd,假设答案为a,b,那么a*b = x且gcd(a,b) = 1,因为均值不等式所以当a越接近sqrt(x),a+b越小. x的范围是int64的,所以要用Pollard_rho ...

  9. iOS 集成支付宝过程中 我遇到的一些坑,请大家注意啦(ALI69错误,ALI64错误)

    支付宝很早一段时间就集成了,之前由于一直忙于开发就没有总结,今天整理桌面的时候看到,当时做支付时候的一些散落的笔记,就稍微整理一下,给大家分享一下. 第一:当时调用支付宝的时候,总是调不起来,进过断点 ...

  10. Spring学习记录(三)

    一.AOP的整理总结 aop面向切面编程 横向重复代码,纵向抽取 动态代理 1.通过动态代理可以体现aop思想 2.为什么要哦用动态代理:对目标对象中的方法进行增强 spring aop开发 spri ...