python__007内置函数

摘要:
Highlight=build#ascii内置函数abs()delattr()hash()memoryview()set()all()dict()help()min()setattr()any()dir()hex()next()slice()ascii()divmod()id()object()sorted()bin()enumerate()input()oct()static method()bool()eval()int()open()str()breakpot int()exec()isinstance()or()sum()bytearray()filter()issubclass()pow()super()bytes()float()iter()print()tuple()callable()format()len()property()type()chr()frozenset()list()range()vars()classmethod()getattr()locals()repr()zip()compile()globals()map()reversed()__import__()complex()hasattr(()max()round()abs返回数字的绝对值。这将生成一个类似于repr()Python 2中返回的字符串。结果是一个有效的Python表达式。如果x不是Python对象,则必须定义返回整数的a__index__()方法。FalseTrueboolintFalseTrue在版本3.7:x中更改,现在仅是位置参数。断点此函数将使您进入调用站点的调试器。具体来说,它调用sys。breakpointhook(),并直接传递args和kws。默认情况下,sys。breakpointhook()调用pdb。set_Trace()不需要参数。3.2版本中的新功能:此功能首先在Python 3.0中删除,然后在Python 3.2中恢复。

本文摘自:https://docs.python.org/3/library/functions.html?highlight=built#ascii

   

  

  

内置功能

  

abs()

delattr()

hash()

memoryview()

set()

all()

dict()

help()

min()

setattr()

any()

dir()

hex()

next()

slice()

ascii()

divmod()

id()

object()

sorted()

bin()

enumerate()

input()

oct()

staticmethod()

bool()

eval()

int()

open()

str()

breakpoint()

exec()

isinstance()

ord()

sum()

bytearray()

filter()

issubclass()

pow()

super()

bytes()

float()

iter()

print()

tuple()

callable()

format()

len()

property()

type()

chr()

frozenset()

list()

range()

vars()

classmethod()

getattr()

locals()

repr()

zip()

compile()

globals()

map()

reversed()

__import__()

complex()

hasattr()

max()

round()

abs

返回数字的绝对值。参数可以是整数或浮点数。如果参数是一个复数,则返回其大小。

all可迭代的

返回True如果的所有元素迭代是真实的(或者如果可迭代为空)。相当于:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
any可迭代的

True如果iterable的任何元素为true ,则返回如果iterable为空,则返回False相当于:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
ascii对象

repr(),由返回的字符串中返回一个包含对象的可打印表示一个字符串,但逃避非ASCII字符 repr()使用xuU逃逸。这会生成一个类似于repr()Python 2 中返回的字符串

bin

将整数转换为前缀为“0b”的二进制字符串。结果是一个有效的Python表达式。如果x不是Python int对象,则必须定义一个__index__()返回整数方法。一些例子:

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

如果需要前缀“0b”,您可以使用以下任一方法。

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')

另请参阅format()以获取更多信息。

class bool

返回一个布尔值,即True或者之一False。 使用标准真值测试程序转换x如果x为false或省略,则返回否则它会返回的 类是的子类(参见数值类型-整数,浮点,复合)。它不能进一步细分。它的唯一实例是和 (参见布尔值)。FalseTrueboolintFalseTrue

在版本3.7中更改:x现在是仅位置参数。

breakpoint* args** kws 

此函数会将您置于调用站点的调试器中。具体来说,它呼叫sys.breakpointhook(),传递argskws直接通过。默认情况下,sys.breakpointhook()调用 pdb.set_trace()不需要参数。在这种情况下,它纯粹是一个便利功能,因此您不必显式导入 pdb或输入尽可能多的代码来进入调试器。但是, sys.breakpointhook()可以设置为其他一些功能并 breakpoint()自动调用它,允许您进入选择的调试器。

版本3.7中的新功能。

class bytearraysource [encoding [errors 

返回一个新的字节数组。bytearray类是整数的范围为0 <= X一个可变的序列<256它具有最的可变序列,在所描述的常规方法的可变序列类型,以及大多数方法,该bytes类型已见字节和ByteArray操作

可选的source参数可用于以几种不同的方式初始化数组:

  • 如果它是一个字符串,您还必须提供编码(和可选的, 错误)参数; bytearray()然后使用将字符串转换为字节str.encode()

  • 如果它是一个整数,则该数组将具有该大小,并将使用空字节进行初始化。

  • 如果它是符合缓冲区接口的对象,则将使用该对象的只读缓冲区来初始化bytes数组。

  • 如果它是可迭代的,则它必须是范围内的可迭代整数 ,它们用作数组的初始内容。<= 256

如果没有参数,则会创建一个大小为0的数组。

另请参见二进制序列类型 - 字节,bytearray,memoryviewBytearray对象

class bytessource [encoding [errors 

返回一个新的“bytes”对象,该对象是该范围内不可变的整数序列。 是一个不可变的版本 - 它具有相同的非变异方法和相同的索引和切片行为。<= 256bytesbytearray

因此,构造函数参数被解释为bytearray()

也可以使用文字创建字节对象,请参阅字符串和字节文字

另请参见二进制序列类型 - 字节,字节数组内存视图字节对象以及字节和字节操作

callable对象

True如果object参数显示为可调用 False返回,否则返回如果返回true,则调用仍然可能失败,但如果调用失败,则调用对象将永远不会成功。请注意,类是可调用的(调用类会返回一个新实例); 如果实例的类具有__call__()方法,则它们是可调用的

版本3.2中的新功能此功能首先在Python 3.0中删除,然后在Python 3.2中恢复。

chr

返回表示Unicode代码点为整数i的字符的字符串例如,chr(97)返回字符串'a',同时 chr(8364)返回字符串'€'这是相反的ord()

参数的有效范围是0到1,114,111(基数为16的0x10FFFF)。 ValueError如果超出该范围,将被提出

@classmethod

将方法转换为类方法。

类方法接收类作为隐式的第一个参数,就像实例方法接收实例一样。要声明一个类方法,请使用此成语:

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...

@classmethod形式是一个函数装饰 -见 函数定义的详细信息。

可以在类(例如C.f())或实例(例如C().f()调用类方法除了类之外,该实例被忽略。如果为派生类调用类方法,则派生类对象将作为隐含的第一个参数传递。

类方法与C ++或Java静态方法不同。如果你想要那些,请参阅staticmethod()

有关类方法的更多信息,请参阅标准类型层次结构

compilesourcefilenamemodeflags = 0dont_inherit = Falseoptimize = -1 

代码编译为代码或AST对象。代码对象可以由exec()执行eval()。 source可以是普通字符串,字节字符串或AST对象。ast有关如何使用AST对象的信息,请参阅模块文档。

文件名参数应该给从代码读取的文件; 如果没有从文件中读取('<string>'通常使用),则传递一些可识别的值

模式参数指定什么样的代码必须进行编译; 它可以是 'exec',如果包含的语句序列的,'eval'如果它由一个单一的表达的,或者'single'如果它由单个交互式声明的(在后一种情况下,计算结果为比其他东西表达式语句None将被打印)。

可选参数flagsdont_inherit控制将来的语句影响的编译如果两者都不存在(或两者都为零),则使用在调用的代码中生效的未来语句编译代码compile()如果 给出flags参数且dont_inherit不是(或为零),那么除了将要使用的那些之外,还使用flags参数指定的future语句如果dont_inherit是一个非零整数,那么flags参数就是它 - 忽略了对编译调用有效的未来语句。

将来的语句由位指定,这些位可以按位OR运算以指定多个语句。指定给定特征所需的位域可以作为模块中实例compiler_flag属性找到_Feature__future__

参数optimize指定编译器的优化级别; 默认值-1选择由-O选项给出的解释器的优化级别显式级别是0(没有优化; __debug__是真的),1(断言被删除,__debug__是假的)或2(文档字符串也被删除)。

SyntaxError如果编译的源无效,并且ValueError源包含空字节此函数引发

如果要将Python代码解析为其AST表示,请参阅 ast.parse()

注意

 

'single'或 'eval'模式下使用多行代码编译字符串时,输入必须至少由一个换行符终止。这有助于检测code模块中不完整和完整的语句

警告

 

由于Python AST编译器中的堆栈深度限制,在编译为AST对象时,可能会使Python解释器崩溃并使用足够大/复杂的字符串。

版本3.2中已更改:允许使用Windows和Mac换行符。'exec'模式下输入也不必再以换行符结束。添加了optimize参数。

在版本3.5中更改:以前TypeError中遇到空字节时引发

class complexreal [imag 

返回值为real + imag * 1j的复数或将字符串或数字转换为复数。如果第一个参数是一个字符串,它将被解释为一个复数,并且必须在没有第二个参数的情况下调用该函数。第二个参数永远不能是字符串。每个参数可以是任何数字类型(包括复数)。如果IMAG被省略,默认为零,并且构造用作数字转换等 intfloat如果省略两个参数,则返回 0j

注意

 

从字符串转换时,字符串不得包含中心+-运算符周围的空格例如, complex('1+2j')很好,但提高 complex('1 2j')ValueError

复杂类型在Numeric Types中描述- int,float,complex

在版本3.6中更改:允许使用下划线对数字进行分组,如代码文字中所示。

delattr对象名称

这是一个亲戚setattr()参数是一个对象和一个字符串。该字符串必须是对象属性之一的名称。如果对象允许,该函数将删除命名属性。例如,相当于delattr(x, 'foobar')del x.foobar

上课dict** kwarg 
class dictmapping** kwarg 
class dictiterable** kwarg 

创建一个新的字典。dict对象是字典类。有关此类的文档,请参阅dict映射类型 - dict

对于其他容器,请参阅内置的 in listset和 tuple类以及collections模块。

dir对象

如果没有参数,则返回当前本地范围中的名称列表。使用参数,尝试返回该对象的有效属性列表。

如果对象具有名为的__dir__()方法,则将调用此方法,并且必须返回属性列表。这允许实现自定义__getattr__()__getattribute__()函数的对象自 定义dir()报告其属性的方式 

如果对象未提供__dir__(),则该函数会尽力从对象的__dict__属性(如果已定义)和其类型对象中收集信息结果列表不一定完整,并且在对象具有自定义时可能不准确__getattr__()

默认dir()机制对不同类型的对象表现不同,因为它尝试生成最相关但非完整的信息:

  • 如果对象是模块对象,则列表包含模块属性的名称。

  • 如果对象是类型或类对象,则列表包含其属性的名称,并且递归地包含其基础的属性。

  • 否则,该列表包含对象的属性名称,其类的属性的名称,以及其类的基类的属性的递归。

结果列表按字母顺序排序。例如:

>>> import struct
>>> dir()   # show the names in the module namespace  # doctest: +SKIP
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module # doctest: +SKIP
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']

注意

 

因为dir()它主要是为了方便在交互式提示中使用而提供的,所以它试图提供一组有趣的名称,而不是尝试提供严格或一致定义的名称集,并且其详细行为可能会在不同版本之间发生变化。例如,当参数是类时,元类属性不在结果列表中。

divmoda

取两个(非复数)数作为参数,并在使用整数除法时返回由商和余数组成的一对数字。对于混合操作数类型,二进制算术运算符的规则适用。对于整数,结果与之相同对于浮点数,结果是,其中q通常但可能比该值小1。在任何情况下非常接近a,如果非零,则它与b具有相同的符号,并且(a // b, b)(q, %b)math.floor(a b)bb<= abs(a b) abs(b)

enumerateiterablestart = 0 

返回一个枚举对象。iterable必须是一个序列,一个 迭代器或一些支持迭代的对象。__next__()返回的迭代器方法 enumerate()返回一个包含计数的元组(从start开始,默认为0)和迭代迭代得到的值

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

相当于:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1
eval表达式globals = Nonelocals = None 

参数是一个字符串和可选的全局变量和本地变量。如果提供, globals必须是字典。如果提供,则locals可以是任何映射对象。

表达参数分析,并作为一个Python表达式来使用(从技术上来说,一个条件列表)全局当地人 的字典作为全局和局部名字空间。如果全局字典存在且不包含键的值,则解析表达式之前,将在该键下插入内置模块的字典的引用这意味着表达式通常具有对标准模块的完全访问权限,并且传播受限制的环境。如果省略locals字典,则默认为globals__builtins__builtinsbuiltins 字典。如果省略两个字典,则表达式在eval()调用的环境中执行返回值是计算表达式的结果。语法错误报告为异常。例:

>>> x = 1
>>> eval('x+1')
2

此函数还可用于执行任意代码对象(例如由其创建的代码对象compile())。在这种情况下,传递代码对象而不是字符串。如果代码对象已经被编译'exec'为 模式的说法,eval()“返回值会None

提示:exec() 函数支持动态执行语句globals()locals()功能返回当前全球和本地词典,分别,其可以是通过以绕过使用有用eval()exec()

请参阅ast.literal_eval()可以安全地使用仅包含文字的表达式来评估字符串的函数。

execobject [globals [locals 

此函数支持Python代码的动态执行。object必须是字符串或代码对象。如果它是一个字符串,则将该字符串解析为一组Python语句,然后执行该语句(除非发生语法错误)。1如果它是代码对象,则只执行它。在所有情况下,执行的代码应该作为文件输入有效(请参见“参考手册”中的“文件输入”部分)。请注意, 即使在传递给函数的代码的上下文中,也不能在函数定义之外使用returnyield语句 exec()返回值是None

在所有情况下,如果省略可选部分,则代码在当前范围内执行。如果只提供全局变量,则它必须是字典,它将用于全局变量和局部变量。如果全局和 当地人给出,它们分别用于全局和局部变量。如果提供,则locals可以是任何映射对象。请记住,在模块级别,全局变量和本地变量是相同的字典。如果exec获得两个单独的对象作为全局变量局部变量,则代码将被执行,就像它嵌入在类定义中一样。

如果全局字典不包含键的值, 则在该键下插入内置模块 的字典的引用这样,您可以通过在传递给自己的字典之前将自己的字典插入到全局变量中来控制已执行代码可用的 内置函数 __builtins__builtins__builtins__exec()

注意

 

 -in功能globals()locals()返回当前的全局和局部字典,分别,这可能是传递用作第二个和第三个参数有用exec()

注意

 

默认的localslocals()下面的函数所述:不应尝试修改默认的locals字典。如果需要在函数返回查看本地代码的效果,则传递显式的本地字典exec()

filter功能可迭代

iterable的那些元素构造一个迭代器函数 返回true。 iterable可以是序列,支持迭代的容器,也可以是迭代器。如果功能None,同样的函数被假定,那就是,所有的元素迭代是假的被删除。

注意,如果函数不是如果函数是 则等效于生成器表达式filter(function, iterable)(item for itemin iterable if function(item))None(item for item in iterable if item)None

请参阅itertools.filterfalse()补充函数,函数返回iterable的元素,函数返回false。

class float

返回由数字或字符串x构造的浮点数

如果参数是一个字符串,它应该包含一个十进制数字,可选地以符号开头,并且可选地嵌入在空格中。可选标志可以是'+''-'一个'+'符号具有上产生的值没有影响。参数也可以是表示NaN(非数字)或正或负无穷大的字符串。更确切地说,在删除前导和尾随空格字符后,输入必须符合以下语法:

sign           :: =“+”| “ - ”
 infinity       :: =“Infinity”| “inf”
 nan            :: =“nan”
 numeric_value :: =   floatnumber| infinity| numeric_string :: = [ ]nan
signnumeric_value

下面floatnumber是浮点文字中描述的Python浮点文字的形式案例并不重要,因此,例如,“inf”,“Inf”,“INFINITY”和“iNfINity”都是正无限的可接受拼写。

否则,如果参数是整数或浮点数,则返回具有相同值的浮点数(在Python的浮点精度内)。如果参数超出了Python float的范围,OverflowError则会引发一个。

对于一般Python对象xfloat(x)委托给 x.__float__()

如果没有给出参数,0.0则返回。

例子:

>>>
>>> float('+1.23')
1.23
>>> float('   -12345
')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf

float类型在Numeric Types中描述- int,float,complex

在版本3.6中更改:允许使用下划线对数字进行分组,如代码文字中所示。

在版本3.7中更改:x现在是仅位置参数。

formatvalue [format_spec 

转换为“格式化”表示,由format_spec控制 format_spec的解释将取决于value参数的类型,但是大多数内置类型都使用标准格式化语法Format Specification Mini-Language

默认的format_spec是一个空字符串,通常与调用具有相同的效果str(value)

转换为 在搜索值的方法时绕过实例字典的调用一 ,如果该方法搜索到达引发异常 format_spec非空,或者这两个 format_spec或返回值是不是字符串。format(value,format_spec)type(value).__format__(value, format_spec)__format__()TypeErrorobject

在版本3.4中更改: 如果format_spec不是空字符串,则object().__format__(format_spec)引发TypeError

class frozensetiterable 

返回一个新frozenset对象,可选地包含从iterable中获取的元素 。 frozenset是一个内置的类。有关此类的文档请参阅frozenset和 设置类型 - set,frozenset

对于其他容器看到内置 -in setlist, tuple,和dict类,还有collections 模块。

getattr对象名称[默认

返回object的named属性的。 name必须是一个字符串。如果字符串是对象属性之一的名称,则结果是该属性的值。例如,相当于 如果named属性不存在,则返回default(如果提供),否则引发。getattr(x,'foobar')x.foobarAttributeError

globals

返回表示当前全局符号表的字典。这始终是当前模块的字典(在函数或方法内部,这是定义它的模块,而不是调用它的模块)。

hasattr对象名称

参数是一个对象和一个字符串。结果是,True如果字符串是对象属性之一的名称,False如果不是。(这是通过调用并查看它是否会引发来实现的。)getattr(object, name)AttributeError

hash对象

返回对象的哈希值(如果有的话)。哈希值是整数。它们用于在字典查找期间快速比较字典键。比较相等的数字值具有相同的哈希值(即使它们具有不同的类型,如1和1.0的情况)。

注意

 

对于具有自定义__hash__()方法的对象,请注意hash() 根据主机的位宽截断返回值。详情__hash__()请见。

help对象

调用内置的帮助系统。(此函数用于交互式使用。)如果未给出参数,则交互式帮助系统将在解释器控制台上启动。如果参数是字符串,则查找字符串作为模块,函数,类,方法,关键字或文档主题的名称,并在控制台上打印帮助页面。如果参数是任何其他类型的对象,则会生成对象的帮助页面。

请注意,如果函数的参数列表中出现斜杠(/),则在调用时help(),意味着斜杠之前的参数仅为位置参数。有关详细信息,请参阅 有关仅位置参数的FAQ条目

此函数模块添加到内置命名空间site

版本3.4中的更改更改为pydoc并且inspect表示报告的可调用签名现在更全面和一致。

hex

将整数转换为带有前缀“0x”的小写十六进制字符串。如果x不是Python int对象,则必须定义一个__index__()返回整数的 方法。一些例子:

>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'

如果要将整数转换为带有前缀或不带前缀的大写或小写十六进制字符串,可以使用以下任一方法:

>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')

另请参阅format()以获取更多信息。

另请参阅int()使用16的基数将十六进制字符串转换为整数。

注意

 

要获取float的十六进制字符串表示形式,请使用该 float.hex()方法。

id对象

返回对象的“标识”。这是一个整数,在该生命周期内保证该对象是唯一且恒定的。具有非重叠寿命的两个对象可以具有相同的id() 值。

CPython实现细节:这是内存中对象的地址。

input提示

如果存在prompt参数,则将其写入标准输出而不带尾随换行符。然后,该函数从输入中读取一行,将其转换为字符串(剥离尾部换行符),然后返回该行。读取EOF时,EOFError会引发。例:

>>>
>>> s = input('--> ')  
--> Monty Python's Flying Circus
>>> s  
"Monty Python's Flying Circus"

如果readline模块已加载,input()则将使用它来提供精细的行编辑和历史记录功能。

class int
class intxbase = 10 

返回由数字或字符串x构造的整数对象0如果没有给出参数,则返回 如果x定义__int__(),则 int(x)返回x.__int__()如果x定义__trunc__(),则返回x.__trunc__()对于浮点数,这会截断为零。

如果X不是数字或如果给出,则X必须是一个字符串, bytesbytearray代表一个实例字面整数在基数可选地,文字可以在+之前-(之间没有空格)并且由空格包围。base-n文字由数字0到n-1组成,a to z(或Ato Z)的值为10到35.默认基数为10.允许的值为0和2-36。Base-2,-8和-16文字可以选择以0b0B, 0o0O0x为前缀0X,与代码中的整数文字一样。基数0表示完全解释为代码文字,因此实际基数为2,8,10或16,因此这是不合法的,同时 也是int('010', 0)int('010')int('010', 8)

整数类型在数值类型中描述- int,float,complex

在版本3.4中更改:如果base不是实例,int并且基础对象具有 base.__index__方法,则调用该方法以获取基础的整数。以前的版本使用 base.__int__而不是base.__index__

在版本3.6中更改:允许使用下划线对数字进行分组,如代码文字中所示。

在版本3.7中更改:x现在是仅位置参数。

isinstance对象classinfo 

如果object参数是classinfo 参数的实例,或者是(直接,间接或虚拟)子类的实例,则返回true 如果object不是给定类型的对象,则该函数始终返回false。如果classinfo是类型对象的元组(或递归,其他此类元组),如果object是任何类型的实例,则返回true 如果classinfo不是类型和类型元组的类型或元组,TypeError则会引发异常。

issubclassclassclassinfo 

如果classclassinfo的子类(直接,间接或虚拟),则返回true 类被认为是其自身的子类。classinfo可以是类对象的元组,在这种情况下,将检查classinfo中的每个条目在任何其他情况下,都会引发异常。TypeError

iter对象[sentinel 

返回一个迭代器对象。根据第二个参数的存在,第一个参数的解释非常不同。如果没有第二个参数,对象必须是支持迭代协议(__iter__()方法)的集合对象,或者它必须支持序列协议(从__getitem__()整数参数开始方法0)。如果它不支持这些协议中的任何一个, TypeError则引发。如果给出第二个参数sentinel,则object必须是可调用对象。在这种情况下创建的迭代器将为每个对其方法的调用调用没有参数的 对象__next__() ; 如果返回的值等于 sentinelStopIteration 将被提出,否则将返回该值。

另请参见迭代器类型

第二种形式的一个有用的应用iter()是构建块读取器。例如,从二进制数据库文件中读取固定宽度的块,直到达到文件末尾:

from functools import partial
with open('mydata.db', 'rb') as f:
    for block in iter(partial(f.read, 64), b''):
        process_block(block)
len

返回对象的长度(项目数)。参数可以是序列(例如字符串,字节,元组,列表或范围)或集合(例如字典,集合或冻结集)。

class listiterable 

实际上,它不是一个函数,而是list一个可变序列类型,如列表序列类型中所述 - 列表,元组,范围

locals

更新并返回表示当前本地符号表的字典。自由变量locals()在函数块中调用时返回,但不在类块中调用。请注意,在模块级别,locals() 并且globals()是相同的字典。

注意

 

不应修改此词典的内容; 更改可能不会影响解释器使用的本地和自由变量的值。

map功能可迭代...... 

返回一个迭代器,它将函数应用于每个iterable,从而产生结果。如果传递了其他可迭代参数,则 函数必须采用那么多参数,并且并行地应用于所有迭代的项。对于多个迭代,迭代器在最短的iterable耗尽时停止。对于函数输入已经安排到参数元组的情况,请参阅itertools.starmap()

maxiterable[keydefault 
maxarg1arg2* args [key 

返回可迭代中的最大项或两个或多个参数中的最大项。

如果提供了一个位置参数,则它应该是可迭代的返回iterable中的最大项。如果提供了两个或多个位置参数,则返回最大的位置参数。

有两个可选的仅关键字参数。关键参数指定一个参数的排序功能,类似于用于list.sort()该 默认参数指定的对象返回如果提供的迭代是空的。如果iterable为空并且未提供default, ValueError则引发a。

如果多个项目是最大的,则该函数返回遇到的第一个项目。这与其他排序稳定性保留工具(例如和)一致 sorted(iterable, key=keyfunc, reverse=True)[0]heapq.nlargest(1, iterable, key=keyfunc)

在新版本3.4:默认情况下只有关键字的说法。

memoryviewobj 

返回从给定参数创建的“内存视图”对象。有关更多信息,请参阅 内存视图

miniterable[keydefault 
minarg1arg2* args [key 

返回可迭代中的最小项或两个或多个参数中的最小项。

如果提供了一个位置参数,则它应该是可迭代的返回iterable中的最小项。如果提供了两个或多个位置参数,则返回最小的位置参数。

有两个可选的仅关键字参数。关键参数指定一个参数的排序功能,类似于用于list.sort()该 默认参数指定的对象返回如果提供的迭代是空的。如果iterable为空并且未提供default, ValueError则引发a。

如果多个项目是最小的,则该函数返回遇到的第一个项目。这与其他排序稳定性保留工具(例如和)一致sorted(iterable, key=keyfunc)[0]heapq.nsmallest(1, iterable, key=keyfunc)

在新版本3.4:默认情况下只有关键字的说法。

next迭代器[默认

通过调用其 方法迭代器中检索下一个项目__next__()如果给定default,则在迭代器耗尽时返回,否则StopIteration引发。

object

返回一个新的无特征对象。 object是所有课程的基础。它具有所有Python类实例共有的方法。此函数不接受任何参数。

注意

 

object没有__dict__,所以你不能指定任意属性的实例object类。

oct

将整数转换为前缀为“0o”的八进制字符串。结果是一个有效的Python表达式。如果x不是Python int对象,则必须定义一个__index__()返回整数方法。例如:

>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'

如果要将整数转换为带有前缀“0o”的八进制字符串,可以使用以下任一方法。

>>> '%#o' % 10, '%o' % 10
('0o12', '12')
>>> format(10, '#o'), format(10, 'o')
('0o12', '12')
>>> f'{10:#o}', f'{10:o}'
('0o12', '12')

另请参阅format()以获取更多信息。

openfilemode ='r'buffering = -1encoding = Noneerrors = Nonenewline = Noneclosefd = Trueopener = None 

打开文件并返回相应的文件对象如果无法打开文件,OSError则引发a。

file是一个类似路径的对象,给出要打开的文件的路径名(绝对或相对于当前工作目录)或要包装的文件的整数文件描述符。(如果给出了文件描述符,则在关闭返回的I / O对象时关闭它,除非将closefd 设置为False。)

mode是一个可选字符串,用于指定打开文件的模式。它默认'r'为在文本模式下打开以进行读取。其他常见值'w'用于写入(如果文件已存在则截断文件),'x'独占创建和'a'附加(在某些 Unix系统上,意味着所有写入都附加到文件末尾而不管当前搜索位置)。在文本模式下,如果 编码未指定使用的编码是与平台相关的:locale.getpreferredencoding(False)被称为获取当前的本地编码。(对于读取和写入原始字节,请使用二进制模式并保留 编码未指定。)可用模式为:

字符

含义

'r'

开放阅读(默认)

'w'

打开写入,先截断文件

'x'

打开以进行独占创建,如果文件已存在则失败

'a'

打开以进行写入,如果存在则附加到文件的末尾

'b'

二进制模式

't'

文字模式(默认)

'+'

打开磁盘文件进行更新(读写)

默认模式是'r'(打开以读取文本,同义词'rt')。对于二进制读写访问,模式'w+b'打开并将文件截断为0字节。 'r+b'打开文件而不截断。

概述中所述,Python区分二进制和文本I / O. 以二进制模式打开的文件(包括'b'mode 参数中)将内容作为bytes对象返回,而不进行任何解码。在文本模式(默认情况下,或者't'包含在mode参数中)时,文件的内容将返回为str,首先使用平台相关编码或使用指定的编码(如果给定)对字节进行解码 

允许使用其他模式字符'U',该字符不再具有任何效果,并且被视为已弃用。它以前在文本模式下启用了 通用换行符,这成为Python 3.0中的默认行为。有关更多详细信息,请参阅newline参数的文档 

注意

 

Python不依赖于底层操作系统的文本文件概念; 所有处理都由Python本身完成,因此与平台无关。

buffering是一个可选的整数,用于设置缓冲策略。传递0以切换缓冲关闭(仅允许在二进制模式下),1选择行缓冲(仅在文本模式下可用),并且整数> 1以指示固定大小的块缓冲区的大小(以字节为单位)。如果没有给出缓冲参数,则默认缓冲策略的工作方式如下:

  • 二进制文件以固定大小的块缓冲; 使用启发式方法选择缓冲区的大小,尝试确定底层设备的“块大小”并重新开始io.DEFAULT_BUFFER_SIZE在许多系统上,缓冲区通常为4096或8192字节长。

  • “交互式”文本文件(isatty() 返回的文件True)使用行缓冲。其他文本文件使用上述策略用于二进制文件。

encoding是用于解码或编码文件的编码的名称。这应该只在文本模式下使用。默认编码取决于平台(无论locale.getpreferredencoding()返回),但可以使用Python支持的任何 文本编码请参阅codecs模块以获取支持的编码列表。

errors是一个可选字符串,用于指定如何处理编码和解码错误 - 这不能在二进制模式下使用。可以使用各种标准错误处理程序(在错误处理程序下列出),但已注册的任何错误处理名称 codecs.register_error()也是有效的。标准名称包括:

  • 'strict'ValueError如果存在编码错误,则引发异常。默认值None具有相同的效果。

  • 'ignore' ignores errors. Note that ignoring encoding errors can lead to data loss.

  • 'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data.

  • 'surrogateescape' will represent any incorrect bytes as code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. These private code points will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding.

  • 'xmlcharrefreplace' is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference &#nnn;.

  • 'backslashreplace' replaces malformed data by Python’s backslashed escape sequences.

  • 'namereplace' (also only supported when writing) replaces unsupported characters with N{...} escape sequences.

newline controls how universal newlines mode works (it only applies to text mode). It can be None''' '' ', and ' '. It works as follows:

  • When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in ' '' ', or ' ', and these are translated into ' ' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

  • When writing output to the stream, if newline is None, any ' ' characters written are translated to the system default line separator, os.linesep. If newline is '' or ' ', no translation takes place. If newline is any of the other legal values, any ' ' characters written are translated to the given string.

If closefd is False and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must be True (the default) otherwise an error will be raised.

A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (fileflags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None).

The newly created file is non-inheritable.

The following example uses the dir_fd parameter of the os.open() function to open a file relative to a given directory:

>>>
>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
...     return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
...     print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd)  # don't leak a file descriptor

The type of file object returned by the open() function depends on the mode. When open() is used to open a file in a text mode ('w''r''wt''rt', etc.), it returns a subclass of io.TextIOBase (specifically io.TextIOWrapper). When used to open a file in a binary mode with buffering, the returned class is a subclass of io.BufferedIOBase. The exact class varies: in read binary mode, it returns an io.BufferedReader; in write binary and append binary modes, it returns an io.BufferedWriter, and in read/write mode, it returns an io.BufferedRandom. When buffering is disabled, the raw stream, a subclass of io.RawIOBaseio.FileIO, is returned.

See also the file handling modules, such as, fileinputio (where open() is declared), osos.pathtempfile, and shutil.

Changed in version 3.3:
  • The opener parameter was added.

  • The 'x' mode was added.

  • IOError used to be raised, it is now an alias of OSError.

  • FileExistsError is now raised if the file opened in exclusive creation mode ('x') already exists.

Changed in version 3.4:
  • The file is now non-inheritable.

Deprecated since version 3.4, will be removed in version 4.0: The 'U' mode.

Changed in version 3.5:
  • If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475for the rationale).

  • The 'namereplace' error handler was added.

Changed in version 3.6:
ord(c)

Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().

pow(xy[, z])

Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x,y) z). The two-argument form pow(x, y) is equivalent to using the power operator: x**y.

The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, 10**2 returns 100, but 10**-2 returns 0.01. If the second argument is negative, the third argument must be omitted. If z is present, x and y must be of integer types, and y must be non-negative.

print(*objectssep=' 'end=' 'file=sys.stdoutflush=False)

Print objects to the text stream file, separated by sep and followed by endsependfile and flush, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sepand followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or Nonesys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

Changed in version 3.3: Added the flush keyword argument.

class property(fget=Nonefset=Nonefdel=Nonedoc=None)

Return a property attribute.

fget is a function for getting an attribute value. fset is a function for setting an attribute value. fdel is a function for deleting an attribute value. And doc creates a docstring for the attribute.

A typical use is to define a managed attribute x:

class C:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")

If c is an instance of Cc.x will invoke the getter, c.x value will invoke the setter and del c.x the deleter.

If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget’s docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator:

class Parrot:
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

The @property decorator turns the voltage() method into a “getter” for a read-only attribute with the same name, and it sets the docstring for voltage to “Get the current voltage.”

A property object has gettersetter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. This is best explained with an example:

class C:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

This code is exactly equivalent to the first example. Be sure to give the additional functions the same name as the original property (x in this case.)

The returned property object also has the attributes fgetfset, and fdel corresponding to the constructor arguments.

Changed in version 3.5: The docstrings of property objects are now writeable.

range(stop)
range(startstop[, step])

Rather than being a function, range is actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.

repr(object)

Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

reversed(seq)

Return a reverse iteratorseq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).

round(number[, ndigits])

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as number.

For a general Python object numberround delegates to number.__round__.

Note

 

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

class set([iterable])

Return a new set object, optionally with elements taken from iterableset is a built-in class. See set and Set Types — set, frozenset for documentation about this class.

For other containers see the built-in frozensetlisttuple, and dict classes, as well as the collectionsmodule.

setattr(objectnamevalue)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar 123.

class slice(stop)
class slice(startstop[, step])

Return a slice object representing the set of indices specified by range(start, stop, step). The start and steparguments default to None. Slice objects have read-only data attributes startstop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.

sorted(iterable*key=Nonereverse=False)

Return a new sorted list from the items in iterable.

Has two optional arguments which must be specified as keyword arguments.

key specifies a function of one argument that is used to extract a comparison key from each element in iterable(for example, key=str.lower). The default value is None (compare the elements directly).

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

For sorting examples and a brief sorting tutorial, see Sorting HOW TO.

@staticmethod

Transform a method into a static method.

A static method does not receive an implicit first argument. To declare a static method, use this idiom:

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

The @staticmethod form is a function decorator – see Function definitions for details.

A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()).

Static methods in Python are similar to those found in Java or C++. Also see classmethod() for a variant that is useful for creating alternate class constructors.

Like all decorators, it is also possible to call staticmethod as a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom:

class C:
    builtin_open = staticmethod(open)

For more information on static methods, see The standard type hierarchy.

class str(object='')
class str(object=b''encoding='utf-8'errors='strict')

Return a str version of object. See str() for details.

str is the built-in string class. For general information about strings, see Text Sequence Type — str.

sum(iterable[, start])

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable’s items are normally numbers, and the start value is not allowed to be a string.

For some use cases, there are good alternatives to sum(). The preferred, fast way to concatenate a sequence of strings is by calling ''.join(sequence). To add floating point values with extended precision, see math.fsum(). To concatenate a series of iterables, consider using itertools.chain().

super([type[, object-or-type]])

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr()except that the type itself is skipped.

The __mro__ attribute of the type lists the method resolution search order used by both getattr() and super(). The attribute is dynamic and can change whenever the inheritance hierarchy is updated.

If the second argument is omitted, the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true (this is useful for classmethods).

There are two typical use cases for super. In a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of super in other programming languages.

The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. Good design dictates that this method have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).

For both use cases, a typical superclass call looks like this:

class C(B):
    def method(self, arg):
        super().method(arg)    # This does the same thing as:
                               # super(C, self).method(arg)

Note that super() is implemented as part of the binding process for explicit dotted attribute lookups such as super().__getitem__(name). It does so by implementing its own __getattribute__() method for searching classes in a predictable order that supports cooperative multiple inheritance. Accordingly, super() is undefined for implicit lookups using statements or operators such as super()[name].

Also note that, aside from the zero argument form, super() is not limited to use inside methods. The two argument form specifies the arguments exactly and makes the appropriate references. The zero argument form only works inside a class definition, as the compiler fills in the necessary details to correctly retrieve the class being defined, as well as accessing the current instance for ordinary methods.

For practical suggestions on how to design cooperative classes using super(), see guide to using super().

tuple([iterable])

Rather than being a function, tuple is actually an immutable sequence type, as documented in Tuples and Sequence Types — list, tuple, range.

class type(object)
class type(namebasesdict)

With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.

The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and is copied to a standard dictionary to become the __dict__ attribute. For example, the following two statements create identical type objects:

>>> class X:
...     a = 1
...
>>> X = type('X', (object,), dict(a=1))

See also Type Objects.

Changed in version 3.6: Subclasses of type which don’t override type.__new__ may no longer use the one-argument form to get the type of an object.

vars([object])

Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write restrictions on their __dict__ attributes (for example, classes use a types.MappingProxyType to prevent direct dictionary updates).

Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

zip(*iterables)

Make an iterator that aggregates elements from each of the iterables.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to:

def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)

The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n). This repeats the same iterator n times so that each output tuple has the result of n calls to the iterator. This has the effect of dividing the input into n-length chunks.

zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. If those values are important, use itertools.zip_longest() instead.

zip() in conjunction with the * operator can be used to unzip a list:

>>>
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
__import__(nameglobals=Nonelocals=Nonefromlist=()level=0)

Note

 

This is an advanced function that is not needed in everyday Python programming, unlikeimportlib.import_module().

This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.__import__) in order to change semantics of the import statement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of __import__() is also discouraged in favor of importlib.import_module().

The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement.

level specifies whether to use absolute or relative imports. 0 (the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling __import__() (see PEP 328 for the details).

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.

For example, the statement import spam results in bytecode resembling the following code:

spam = __import__('spam', globals(), locals(), [], 0)

The statement import spam.ham results in this call:

spam = __import__('spam.ham', globals(), locals(), [], 0)

Note how __import__() returns the toplevel module here because this is the object that is bound to a name by the import statement.

On the other hand, the statement from spam.ham import eggs, sausage as saus results in

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage

Here, the spam.ham module is returned from __import__(). From this object, the names to import are retrieved and assigned to their respective names.

If you simply want to import a module (potentially within a package) by name, use importlib.import_module().

Changed in version 3.3: Negative values for level are no longer supported (which also changes the default value to 0).

Footnotes

1

请注意,解析器只接受Unix风格的行尾约定。如果您正在从文件中读取代码,请确保使用换行转换模式来转换Windows或Mac样式的换行符。

免责声明:文章转载自《python__007内置函数》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇qt--- vs[转]概率漫谈下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

【Crash】C++程序崩溃排查方法

windows下C++程序release版本崩溃错误排查方法。 一个你精心设计的24小时不间断运行,多线程的程序,突然运行了几个月后崩了,此问题是非常难以排查的,也是很头疼的问题。 现利用Google开源工具crashrpt与Microsoft windbg工具,解决这个问题,并分享给大家。 使用工具Crashrpt、Windbg.因为windbg这个工...

浅谈Python-IO多路复用(select、poll、epoll模式)

1. 什么是IO多路复用   在传统socket通信中,存在两种基本的模式,   第一种是同步阻塞IO,其线程在遇到IO操作时会被挂起,直到数据从内核空间复制到用户空间才会停止,因为对CPython来说,很多socket相关函数均是与内核函数(系统调用)密切相关的,比如fctl与ioctl,那么采用这种模式就会存在CPU资源利用率变低,具体的模式图如下:...

以“图片渐入渐出”为例讲述jQuery插件的具体实现

首先声明,此代码以网友“斯迈欧”原创作为此例的讲解; 在这之前我们先看看我们要做的效果是什么样的: 解析下面的样式:我们要图片在过“一定时间”后自动切换,在右下角处有小方块似数字1,2,3,4,这些数字是根据图片的个数自动出现的,当鼠标经过的时候数字颜色有一定的变化; 下面我们来看看具体怎么实现。 第一步:先写简单的html页面 <!DOCTYPE...

关于Delphi中的字符串的浅析(瓢虫大作,里面有内存错误的举例)

关于Delphi中的字符串的浅析 只是浅浅的解析下,让大家可以快速的理解字符串。 其中的所有代码均在Delphi7下测试通过。 Delphi 4,5,6,7中有字符串类型包括了: 短字符串(Short String) 长字符串(Long String) 宽字符串(Wide String) 零结尾字符串(Null-Terminated String)、P...

关于窗口重画的初级问题

关于窗口重画的初级问题 初初级问题: 我在视图画的图象或者文字,当窗口改变后(包括最小化后还原,被别的窗口挡住后重新显示等)为什么不见了? 这 就是窗口重绘或者说重画的问题。当窗口改变后,会产生无效区域,这个无效的区域需要重画。什么是无效区域?自己到网上搜索或者看相关资料。我这里给出一个 特殊的解释:以最小化后还原为例,假设只有一个程序在运行,窗口最小化时...

VC6.0设置选项解读(转)

其实软件调试还是一个技术熟练过程,得慢慢自己总结,可以去搜索引擎查找一些相关的文章看看,下边是一篇关于VC6使用的小文章,贴出来大家看看: 大家可能一直在用VC开发软件,但是对于这个编译器却未必很了解。原因是多方面的。大多数情况下,我们只停留在“使用”它,而不会想去“了解”它。因为它只是一个工具,我们宁可把更多的精力放在C++语言和软件设计上。我们习惯于这...