一、内置函数
Python内置了函数,它们按字母顺序排列如下:
内置函数 | ||||
abs() | delattr() | help() | next() | slice() |
all() | dict() | hex() | object() | sorted() |
any() | dir() | id() | oct() | staticmethod() |
ascii() | divmod() | input() | open() | str() |
apply() | enumerate() | int() | ord() | sum() |
basestring() | eval() | intern() | pow() | super() |
bin() | exec() | isinstance() | print() | tuple() |
bool() | execfile() | issubclass() | property() | type() |
buffer() | file() | iter() | range() | unichr() |
bytearray() | filter() | len() | raw_input() | unicode() |
callable() | float() | list() | reduce() | vars() |
chr() | format() | locals() | reload() | xrange() |
classmethod() | frozenset() | long() | repr() | zip() |
cmp() | getattr() | map() | reversed() | __import__() |
coerce() | globals() | max() | round() | |
compile() | hasattr() | memoryview() | set() | |
complex() | hash() | min() | setattr() |
黄色python3新增,标记红色python2特有,标记绿色python2特有但非通用函数;
官方链接如下:;
各内置函数按照功能划分,可分为数学运算、集合类操作、逻辑判断、反射、IO操作、非通用、其他;
二、数学运算
函数名 | 备注 |
abs(x) | 求绝对值 1、参数可以是整型,也可以是复数 2、若参数是复数,则返回复数的模 |
complex([real[, imag]]) | 创建一个复数 |
divmod(a, b) | 分别取商和余数 注意:整型、浮点型都可以 |
float([x]) | 将一个字符串或数转换为浮点数。如果无参数将返回0.0 |
int([x[, base]]) | 将一个字符转换为int类型,base表示进制 |
long([x[, base]]) | 将一个字符转换为long类型 |
pow(x, y[, z]) | 返回x的y次幂 |
range([start], stop[, step]) | 产生一个序列,默认从0开始 |
round(x[, n]) | 四舍五入 |
sum(iterable[, start]) | 对集合求和 |
oct(x) | 将一个数字转化为8进制 |
hex(x) | 将整数x转换为16进制字符串 |
chr(i) | 返回整数i对应的ASCII字符 |
bin(x) | 将整数x转换为二进制字符串 |
bool([x]) | 将x转换为Boolean类型 |
1、abs函数说明
def abs(number): # real signature unknown; restored from __doc__ """ abs(number) -> number Return the absolute value of the argument. """ return 0
返回数字的绝对值,参数可以是整数或浮点数,如果参数是复数,则返回其大小;
例如:
>>> x = -1
>>> abs(x)
1
>>> x = 1.1
>>> abs(x)
1.1
2、complex函数说明
class complex(object): """ complex(real[, imag]) -> complex number 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. """ def conjugate(self): # real signature unknown; restored from __doc__ """ complex.conjugate() -> complex Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j. """ return complex def __abs__(self): # real signature unknown; restored from __doc__ """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __coerce__(self, y): # real signature unknown; restored from __doc__ """ x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): # real signature unknown; restored from __doc__ """ x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): # real signature unknown; restored from __doc__ """ x.__div__(y) <==> x/y """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __float__(self): # real signature unknown; restored from __doc__ """ x.__float__() <==> float(x) """ pass def __floordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__floordiv__(y) <==> x//y """ pass def __format__(self): # real signature unknown; restored from __doc__ """ complex.__format__() -> str Convert to a string according to format_spec. """ return "" def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, real, imag=None): # real signature unknown; restored from __doc__ pass def __int__(self): # real signature unknown; restored from __doc__ """ x.__int__() <==> int(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __long__(self): # real signature unknown; restored from __doc__ """ x.__long__() <==> long(x) """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> xx%y """ pass def __mul__(self, y): # real signature unknown; restored from __doc__ """ x.__mul__(y) <==> x*y """ pass def __neg__(self): # real signature unknown; restored from __doc__ """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __nonzero__(self): # real signature unknown; restored from __doc__ """ x.__nonzero__() <==> x != 0 """ pass def __pos__(self): # real signature unknown; restored from __doc__ """ x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): # real signature unknown; restored from __doc__ """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): # real signature unknown; restored from __doc__ """ x.__radd__(y) <==> y+x """ pass def __rdivmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rfloordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rfloordiv__(y) <==> y//x """ pass def __rmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): # real signature unknown; restored from __doc__ """ x.__rmul__(y) <==> y*x """ pass def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__ """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rsub__(self, y): # real signature unknown; restored from __doc__ """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): # real signature unknown; restored from __doc__ """ x.__rtruediv__(y) <==> y/x """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass def __sub__(self, y): # real signature unknown; restored from __doc__ """ x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): # real signature unknown; restored from __doc__ """ x.__truediv__(y) <==> x/y """ pass imag = property(lambda self: 0.0) """the imaginary part of a complex number :type: float """ real = property(lambda self: 0.0) """the real part of a complex number :type: float """complex
创建一个值为real + imag * j的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数;
- 参数real: int, long, float或字符串;
- 参数imag: int, long, float;
例如:
>>> complex(1, 2)
(1 + 2j)
#数字
>>> complex(1)
(1 + 0j)
#当做字符串处理
>>> complex("1")
(1 + 0j)
#注:这个地方在“+”号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错;
>>> complex("1+2j")
(1 + 2j)
all函数说明
def all(iterable): # real signature unknown; restored from __doc__ """ all(iterable) -> bool Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True. """ return False
所有(可迭代)如果迭代器的所有元素都为真(或者如果迭代器为空),则返回True,即如果iterable的所有元素不为0、''、False或者iterable为空,all(iterable)返回True,否则返回False;
函数等价于:
def all(iterable): for element in iterable: if not element: return False return True
例如:
#列表list,元素都不为空或0>>> all(['a', 'b', 'c', 'd']) True #列表list,存在一个为空的元素>>> all(['a', 'b', '', 'd']) False #列表list,存在一个为0的元素>>> all([0, 1,2, 3]) False #元组tuple,元素都不为空或0>>> all(('a', 'b', 'c', 'd')) True #元组tuple,存在一个为空的元素>>> all(('a', 'b', '', 'd')) False #元组tuple,存在一个为0的元素>>> all((0, 1,2, 3)) False #空列表>>> all([]) True #空元组>>> all(()) True3、ascii函数说明
def ascii(*args, **kwargs): # real signature unknown """ Return an ASCII-only representation of an object. As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \\x, \\u or \\U escapes. This generates a string similar to that returned by repr() in Python 2. """ pass
python3新增函数
这个函数跟repr()函数一样,返回一个可打印的对象字符串方式表示。当遇到非ASCII码时,就会输出\x,\u或\U等字符来表示。与Python 2版本里的repr()是等效的函数。
例如:>>> print(ascii(10), ascii(9000000), ascii('b\31'), ascii('0x\1000'))
10 9000000 'b\x19' '0x@0'
4、any函数说明
def any(iterable): # real signature unknown; restored from __doc__ """ any(iterable) -> bool Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False. """ return False
如果iterable的任何元素为True,则返回True。如果iterable为空,返回False;即如果iterable的任何元素不为0、''、False、all(iterable)返回True。如果iterable为空,返回False。
函数等价于:
def any(iterable): for element in iterable: if element: return False return True
注:该函数与all()函数的区别,any是任意,而all是全部。
例如:
#列表list,元素都不为空或0
>>> any(['a', 'b', 'c', 'd'])
True
#列表list,存在一个为空的元素
>>> any(['a', 'b', '', 'd'])
True
#列表list,元素全为0,'',false
>>> any([0, '', False])
False
#元组tuple,元素都不为空或0
>>> any(('a', 'b', 'c', 'd'))
True
#元组tuple,存在一个为空的元素
>>> any(('a', 'b', '', 'd'))
True
#元组tuple,元素全为0,'',false
>>> any((0, '', False))
False
#空列表
>>> any([])
False
#空元组
>>> any(())
False
5、apply函数说明
def apply(p_object, args=None, kwargs=None): # real signature unknown; restored from __doc__ """ apply(object[, args[, kwargs]]) -> value Call a callable object with positional arguments taken from the tuple args, and keyword arguments taken from the optional dictionary kwargs. Note that classes are callable, as are instances with a __call__() method. Deprecated since release 2.3. Instead, use the extended call syntax: function(*args, **keywords). """ pass
python2特有但非通用函数
apply()函数将args参数应用到function上。function参数必须是可调用对象(函数、方法或其他可调用对象),args参数必须以序列形式给出,列表在应用之前被转换为元组,function对象在被调用时,将args列表的内容分别作为独立的参数看待。
例如:
apply(add,(1,3,4))
等价于
add(1,3,4)
在以列表或元组定义了一列参数,且需要将此列表参数分别作为个个独立参数使用的情况下,必须使用apply()函数。在要把变长参数列应用到该函数上时,apply()函数非常有用。
可选项keywords参数应是个字典,字典的关键字是字符串。这些字符串在apply()函数的参数列末尾处给出,它们将被用作关键字参数。
6、basestring函数说明
class basestring(object): """ Type basestring cannot be instantiated; it is the base for str and unicode. """ def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass
python2特有函数
basestring是str和unicode的超类(父类),也是抽象类,因此不能被调用和实例化,但可以被用来判断一个对象是否为str或者unicode的实例,isinstance(obj, basestring)等价于isinstance(obj, (str, unicode));
例如:
>>> isinstance("Hello world", str)
True
>>> isinstance("Hello world", basestring)
True
>>> isinstance(u"你好", unicode)
True
>>> isinstance(u"你好", basestring)
True
7、bin函数说明
def bin(number): # real signature unknown; restored from __doc__ """ bin(number) -> string Return the binary representation of an integer or long integer. """ return ""
将整数x转换为二进制字符串,如果x不为Python中int类型,x必须包含方法__index__()并且返回值为integer;参数x需为整数或者包含__index__()方法切返回值为integer的类型;
例如:
#整数的情况
>>> bin(521)
#这里的显示结果形式与我们平时习惯有些差别,主要是前面多了0b,这是表示二进制的意思。
'0b1000001001'
#非整型的情况,必须包含__index__()方法切返回值为integer的类型
>>> class myType:
... def __index__(self):
... return 35
>>> myvar = myType()
>>> bin(myvar)
'0b1000001001'
8、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. """ def __and__(self, y): # real signature unknown; restored from __doc__ """ x.__and__(y) <==> x&y """ pass def __init__(self, x): # real signature unknown; restored from __doc__ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __or__(self, y): # real signature unknown; restored from __doc__ """ x.__or__(y) <==> x|y """ pass def __rand__(self, y): # real signature unknown; restored from __doc__ """ x.__rand__(y) <==> y&x """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __ror__(self, y): # real signature unknown; restored from __doc__ """ x.__ror__(y) <==> y|x """ pass def __rxor__(self, y): # real signature unknown; restored from __doc__ """ x.__rxor__(y) <==> y^x """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass def __xor__(self, y): # real signature unknown; restored from __doc__ """ x.__xor__(y) <==> x^y """ pass
返回布尔值,即True或False之一,x使用标准真值测试程序转换;
如果x为false或省略,则返回False,否则返回True;
bool也是一个类,它是int的子类;
bool类不能进一步子类化,它的唯一实例是False和True;
例如:
>>> bool(0)
False
>>> bool("abc")
True
>>> bool("")
False
>>> bool([])
False
>>> bool()
False
#bool是一个subclass int
>>> issubclass(bool, int)
True
9、buffer函数说明
class buffer(object): """ buffer(object [, offset[, size]]) Create a new buffer object which references the given object. The buffer will reference a slice of the target object from the start of the object (or at the specified offset). The slice will extend to the end of the target object (or with the specified size). """ def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __delslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__delslice__(i, j) <==> del x[i:j] Use of negative indices is not supported. """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, p_object, offset=None, size=None): # real signature unknown; restored from __doc__ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__ """ x.__setslice__(i, j, y) <==> x[i:j]=y Use of negative indices is not supported. """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass
python2特有但非通用函数
如果object对象支持缓存调用接口,buffer()函数就为object对象创建一个新缓存,这样的对象包括字符串、数组和缓存;
该新缓存通过使用从offset参数值开始直到该对象末尾的存储片段或从offset参数值开始直到size参数给出的尺寸为长度的存储片段来引用object对象,如果没给出任何选项参数,缓存区域就覆盖整个序列,最终得到的缓存对象是object对象数据的只读拷贝;
缓存对象用于给某个对象类型创建一个更友好的接口。比如,字符串对象类型通用缓存对象而变得可用,允许逐个字节地访问字符串中的信息;
10、bytearray函数说明
class bytearray(object): """ bytearray(iterable_of_ints) -> bytearray. bytearray(string, encoding[, errors]) -> bytearray. bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray. bytearray(memory_view) -> bytearray. Construct a mutable bytearray object from: - an iterable yielding integers in range(256) - a text string encoded using the specified encoding - a bytes or a bytearray object - any object implementing the buffer API. bytearray(int) -> bytearray. Construct a zero-initialized bytearray of the given length. """ def append(self, p_int): # real signature unknown; restored from __doc__ """ B.append(int) -> None Append a single item to the end of B. """ pass def capitalize(self): # real signature unknown; restored from __doc__ """ B.capitalize() -> copy of B Return a copy of B with only its first character capitalized (ASCII) and the rest lower-cased. """ pass def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ B.center(width[, fillchar]) -> copy of B Return B centered in a string of length width. Padding is done using the specified fill character (default is a space). """ pass def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ B.count(sub [,start [,end]]) -> int Return the number of non-overlapping occurrences of subsection sub in bytes B[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return 0 def decode(self, encoding=None, errors=None): # real signature unknown; restored from __doc__ """ B.decode([encoding[, errors]]) -> unicode object. Decodes B using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. """ return u"" def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ B.endswith(suffix [,start [,end]]) -> bool Return True if B ends with the specified suffix, False otherwise. With optional start, test B beginning at that position. With optional end, stop comparing B at that position. suffix can also be a tuple of strings to try. """ return False def expandtabs(self, tabsize=None): # real signature unknown; restored from __doc__ """ B.expandtabs([tabsize]) -> copy of B Return a copy of B where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ pass def extend(self, iterable_int): # real signature unknown; restored from __doc__ """ B.extend(iterable int) -> None Append all the elements from the iterator or sequence to the end of B. """ pass def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ B.find(sub [,start [,end]]) -> int Return the lowest index in B where subsection sub is found, such that sub is contained within B[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 @classmethod # known case def fromhex(cls, string): # real signature unknown; restored from __doc__ """ bytearray.fromhex(string) -> bytearray Create a bytearray object from a string of hexadecimal numbers. Spaces between two numbers are accepted. Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\xb9\x01\xef'). """ return bytearray def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ B.index(sub [,start [,end]]) -> int Like B.find() but raise ValueError when the subsection is not found. """ return 0 def insert(self, index, p_int): # real signature unknown; restored from __doc__ """ B.insert(index, int) -> None Insert a single item into the bytearray before the given index. """ pass def isalnum(self): # real signature unknown; restored from __doc__ """ B.isalnum() -> bool Return True if all characters in B are alphanumeric and there is at least one character in B, False otherwise. """ return False def isalpha(self): # real signature unknown; restored from __doc__ """ B.isalpha() -> bool Return True if all characters in B are alphabetic and there is at least one character in B, False otherwise. """ return False def isdigit(self): # real signature unknown; restored from __doc__ """ B.isdigit() -> bool Return True if all characters in B are digits and there is at least one character in B, False otherwise. """ return False def islower(self): # real signature unknown; restored from __doc__ """ B.islower() -> bool Return True if all cased characters in B are lowercase and there is at least one cased character in B, False otherwise. """ return False def isspace(self): # real signature unknown; restored from __doc__ """ B.isspace() -> bool Return True if all characters in B are whitespace and there is at least one character in B, False otherwise. """ return False def istitle(self): # real signature unknown; restored from __doc__ """ B.istitle() -> bool Return True if B is a titlecased string and there is at least one character in B, i.e. uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. """ return False def isupper(self): # real signature unknown; restored from __doc__ """ B.isupper() -> bool Return True if all cased characters in B are uppercase and there is at least one cased character in B, False otherwise. """ return False def join(self, iterable_of_bytes): # real signature unknown; restored from __doc__ """ B.join(iterable_of_bytes) -> bytes Concatenates any number of bytearray objects, with B in between each pair. """ return "" def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ B.ljust(width[, fillchar]) -> copy of B Return B left justified in a string of length width. Padding is done using the specified fill character (default is a space). """ pass def lower(self): # real signature unknown; restored from __doc__ """ B.lower() -> copy of B Return a copy of B with all ASCII characters converted to lowercase. """ pass def lstrip(self, bytes=None): # real signature unknown; restored from __doc__ """ B.lstrip([bytes]) -> bytearray Strip leading bytes contained in the argument. If the argument is omitted, strip leading ASCII whitespace. """ return bytearray def partition(self, sep): # real signature unknown; restored from __doc__ """ B.partition(sep) -> (head, sep, tail) Searches for the separator sep in B, and returns the part before it, the separator itself, and the part after it. If the separator is not found, returns B and two empty bytearray objects. """ pass def pop(self, index=None): # real signature unknown; restored from __doc__ """ B.pop([index]) -> int Remove and return a single item from B. If no index argument is given, will pop the last value. """ return 0 def remove(self, p_int): # real signature unknown; restored from __doc__ """ B.remove(int) -> None Remove the first occurrence of a value in B. """ pass def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ """ B.replace(old, new[, count]) -> bytes Return a copy of B with all occurrences of subsection old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. """ return "" def reverse(self): # real signature unknown; restored from __doc__ """ B.reverse() -> None Reverse the order of the values in B in place. """ pass def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ B.rfind(sub [,start [,end]]) -> int Return the highest index in B where subsection sub is found, such that sub is contained within B[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ B.rindex(sub [,start [,end]]) -> int Like B.rfind() but raise ValueError when the subsection is not found. """ return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ B.rjust(width[, fillchar]) -> copy of B Return B right justified in a string of length width. Padding is done using the specified fill character (default is a space) """ pass def rpartition(self, sep): # real signature unknown; restored from __doc__ """ B.rpartition(sep) -> (head, sep, tail) Searches for the separator sep in B, starting at the end of B, and returns the part before it, the separator itself, and the part after it. If the separator is not found, returns two empty bytearray objects and B. """ pass def rsplit(self, sep, maxsplit=None): # real signature unknown; restored from __doc__ """ B.rsplit(sep[, maxsplit]) -> list of bytearray Return a list of the sections in B, using sep as the delimiter, starting at the end of B and working to the front. If sep is not given, B is split on ASCII whitespace characters (space, tab, return, newline, formfeed, vertical tab). If maxsplit is given, at most maxsplit splits are done. """ return [] def rstrip(self, bytes=None): # real signature unknown; restored from __doc__ """ B.rstrip([bytes]) -> bytearray Strip trailing bytes contained in the argument. If the argument is omitted, strip trailing ASCII whitespace. """ return bytearray def split(self, sep=None, maxsplit=None): # real signature unknown; restored from __doc__ """ B.split([sep[, maxsplit]]) -> list of bytearray Return a list of the sections in B, using sep as the delimiter. If sep is not given, B is split on ASCII whitespace characters (space, tab, return, newline, formfeed, vertical tab). If maxsplit is given, at most maxsplit splits are done. """ return [] def splitlines(self, keepends=False): # real signature unknown; restored from __doc__ """ B.splitlines(keepends=False) -> list of lines Return a list of the lines in B, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ return [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ """ B.startswith(prefix [,start [,end]]) -> bool Return True if B starts with the specified prefix, False otherwise. With optional start, test B beginning at that position. With optional end, stop comparing B at that position. prefix can also be a tuple of strings to try. """ return False def strip(self, bytes=None): # real signature unknown; restored from __doc__ """ B.strip([bytes]) -> bytearray Strip leading and trailing bytes contained in the argument. If the argument is omitted, strip ASCII whitespace. """ return bytearray def swapcase(self): # real signature unknown; restored from __doc__ """ B.swapcase() -> copy of B Return a copy of B with uppercase ASCII characters converted to lowercase ASCII and vice versa. """ pass def title(self): # real signature unknown; restored from __doc__ """ B.title() -> copy of B Return a titlecased version of B, i.e. ASCII words start with uppercase characters, all remaining cased characters have lowercase. """ pass def translate(self, table, deletechars=None): # real signature unknown; restored from __doc__ """ B.translate(table[, deletechars]) -> bytearray Return a copy of B, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a bytes object of length 256. """ return bytearray def upper(self): # real signature unknown; restored from __doc__ """ B.upper() -> copy of B Return a copy of B with all ASCII characters converted to uppercase. """ pass def zfill(self, width): # real signature unknown; restored from __doc__ """ B.zfill(width) -> copy of B Pad a numeric string B with zeros on the left, to fill a field of the specified width. B is never truncated. """ pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __alloc__(self): # real signature unknown; restored from __doc__ """ B.__alloc__() -> int Returns the number of bytes actually allocated. """ return 0 def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x """ pass def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __iadd__(self, y): # real signature unknown; restored from __doc__ """ x.__iadd__(y) <==> x+=y """ pass def __imul__(self, y): # real signature unknown; restored from __doc__ """ x.__imul__(y) <==> x*=y """ pass def __init__(self, source=None, encoding=None, errors='strict'): # known special case of bytearray.__init__ """ bytearray(iterable_of_ints) -> bytearray. bytearray(string, encoding[, errors]) -> bytearray. bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray. bytearray(memory_view) -> bytearray. Construct a mutable bytearray object from: - an iterable yielding integers in range(256) - a text string encoded using the specified encoding - a bytes or a bytearray object - any object implementing the buffer API. bytearray(int) -> bytearray. Construct a zero-initialized bytearray of the given length. # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> xx*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ Return state information for pickling. """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ B.__sizeof__() -> int Returns the size of B in memory, in bytes """ return 0 def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass
返回一个新的byte数组, bytearray类是在0 <= x <256范围内的整数的可变序列;
可选的source参数可以用于以几种不同的方式初始化数组:
- 如果source为整数,则返回一个长度为source的初始化数组;
- 如果source为字符串,则按照指定的encoding将字符串转换为字节序列;
- 如果source为可迭代类型,则元素必须为[0 ,255]中的整数;
- 如果source为与buffer接口一致的对象,则此对象也可以被用于初始化bytearray;
如果没有参数,将创建大小为0的数组;
例如:
>>> a = bytearray(3)
>>> a
bytearray(b'\x00\x00\x00')
>>> a[0]
>>> a[1]
>>> a[2]
>>> b = bytearray("abc")
>>> b
bytearray(b'abc')
>>> b[0]
>>> b[1]
>>> b[2]
>>> c = bytearray([1, 2, 3])
>>> c
bytearray(b'\x01\x02\x03')
>>> c[0]
>>> c[1]
>>> c[2]
>>> d = bytearray(buffer("abc"))
>>> d
bytearray(b'abc')
>>> d[0]
>>> d[1]
>>> d[2]
11、callable函数说明
def callable(p_object): # real signature unknown; restored from __doc__ """ callable(object) -> bool Return whether the object is callable (i.e., some kind of function). Note that classes are callable, as are instances with a __call__() method. """ return False
检查对象object是否可调用。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。
注:类是可调用的,而类的实例实现了__call__()方法才可调用。
例如:
>>> callable(0)
False
>>> callable("mystring")
False
>>> def add(a, b):
… return a + b
…
>>> callable(add)
True
>>> class A:
… def method(self):
… return 0
…
>>> callable(A)
True
>>> a = A()
>>> callable(a)
False
>>> class B:
… def __call__(self):
… return 0
…
>>> callable(B)
True
>>> b = B()
>>> callable(b)
True
12、chr函数说明
def chr(i): # real signature unknown; restored from __doc__ """ chr(i) -> character Return a string of one character with ordinal i; 0 <= i < 256. """ return ""
返回一个字符,其ASCII码为整数i。例如chr(97)返回字符串'a',与ord()作用相反,参数必须在[0..255]范围内,如果i超出该范围,将引发ValueError;
例如:
>>> chr(97)
'a'
>>> chr(98)
'b'
>>> ord('a')
97
>>> ord('b')
98
13、classmethod函数说明
class classmethod(object): """ classmethod(function) -> method Convert a function to be a class method. A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom: class C: @classmethod def f(cls, arg1, arg2, ...): ... It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. Class methods are different than C++ or Java static methods. If you want those, see the staticmethod builtin. """ def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __get__(self, obj, type=None): # real signature unknown; restored from __doc__ """ descr.__get__(obj[, type]) -> value """ pass def __init__(self, function): # real signature unknown; restored from __doc__ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass __func__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
classmethod是用来指定一个类的方法为类方法,没有此参数指定的类的方法为实例方法,使用方法如下:
class C: @classmethod def f(cls, arg1, arg2, ...):...
类方法既可以直接类调用(C.f()),也可以进行实例调用(C().f());
例如:
>>> class C:
... @classmethod
... def f(self):
...
print "This is a class method"
...
>>> C.f() This is a class method
>>> c = C()
>>> c.f() This is a class method
>>> class D:
... def f(self):
...
print " This is not a class method "
...
>>> D.f() Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with D instance as first argument (got nothing instead)
>>> d = D()
>>> d.f()
This is not a class method
14、cmp函数说明
def cmp(x, y): # real signature unknown; restored from __doc__ """ cmp(x, y) -> integer Return negative if xy. """ return 0
python2特有函数
比较两个对象x和y,并根据结果返回一个整数;如果x <y,返回值为负;如果x == y,返回值为零;如果x> y,则返回值为正数;
例如:
>>> cmp(1, 2)
-1
>>> cmp(1, 1)
0
>>> cmp(5, 2)
1
>>> cmp('abcd','a')
1
#注:这时候它会先比较第一个字符,然后比较第二个字符,逐个比较知道能判断出大小为止;
15、coerce函数说明
def coerce(x, y): # real signature unknown; restored from __doc__ """ coerce(x, y) -> (x1, y1) Return a tuple consisting of the two numeric arguments converted to a common type, using the same rules as used by arithmetic operations. If coercion is not possible, raise TypeError. """ pass
python2特有但非通用函数
数据类型转换函数,返回一个包含类型转换完毕的两个数值元素的元组;
- 如果有一个x是复数, 则y被转换为复数。
- 如果有一个x是浮点数, 则y被转换为浮点数。
- 如果有一个x是长整数,则y被转换为长整数;
- 如果x及y都是普通整数,无须类型转换;
例如:
>>> coerce(1,2)
(1, 2)
>>>
>>> coerce(1.3,134L)
(1.3, 134.0)
>>>
>>> coerce(1,134L)
(1L, 134L)
>>> coerce(1.23-41j,134L)
((1.23-41j), (134+0j))
16、compile函数说明
def compile(source, filename, mode, flags=None, dont_inherit=None): # real signature unknown; restored from __doc__ """ compile(source, filename, mode[, flags[, dont_inherit]]) -> code object Compile the source string (a Python module, statement or expression) into a code object that can be executed by the exec statement or eval(). The filename will be used for run-time error messages. The mode must be 'exec' to compile a module, 'single' to compile a single (interactive) statement, or 'eval' to compile an expression. The flags argument, if present, controls which future statements influence the compilation of the code. The dont_inherit argument, if non-zero, stops the compilation inheriting the effects of any future statements in effect in the code calling compile; if absent or zero these statements do influence the compilation, in addition to any features explicitly specified. """ pass
将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值;
- 参数source:字符串或者AST(Abstract Syntax Trees)对象;
- 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值;
- 参数model:指定编译代码的种类。可以指定为 ‘exec’,’eval’,’single’;
- 参数flag和dont_inherit:这两个参数暂不介绍,可选参数;
例如:
>>> code = "for i in range(0, 10): print i"
>>> cmpcode = compile(code, '', 'exec')
>>> exec cmpcode
0
1
2
3
4
5
6
7
8
9
>>> str = "3 * 4 + 5"
>>> a = compile(str,'','eval')
>>> eval(a)
17
17、complex函数说明
class complex(object): """ complex(real[, imag]) -> complex number 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. """ def conjugate(self): # real signature unknown; restored from __doc__ """ complex.conjugate() -> complex Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j. """ return complex def __abs__(self): # real signature unknown; restored from __doc__ """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __coerce__(self, y): # real signature unknown; restored from __doc__ """ x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): # real signature unknown; restored from __doc__ """ x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): # real signature unknown; restored from __doc__ """ x.__div__(y) <==> x/y """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __float__(self): # real signature unknown; restored from __doc__ """ x.__float__() <==> float(x) """ pass def __floordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__floordiv__(y) <==> x//y """ pass def __format__(self): # real signature unknown; restored from __doc__ """ complex.__format__() -> str Convert to a string according to format_spec. """ return "" def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, real, imag=None): # real signature unknown; restored from __doc__ pass def __int__(self): # real signature unknown; restored from __doc__ """ x.__int__() <==> int(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __long__(self): # real signature unknown; restored from __doc__ """ x.__long__() <==> long(x) """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> xx%y """ pass def __mul__(self, y): # real signature unknown; restored from __doc__ """ x.__mul__(y) <==> x*y """ pass def __neg__(self): # real signature unknown; restored from __doc__ """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __nonzero__(self): # real signature unknown; restored from __doc__ """ x.__nonzero__() <==> x != 0 """ pass def __pos__(self): # real signature unknown; restored from __doc__ """ x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): # real signature unknown; restored from __doc__ """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): # real signature unknown; restored from __doc__ """ x.__radd__(y) <==> y+x """ pass def __rdivmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rfloordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rfloordiv__(y) <==> y//x """ pass def __rmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): # real signature unknown; restored from __doc__ """ x.__rmul__(y) <==> y*x """ pass def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__ """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rsub__(self, y): # real signature unknown; restored from __doc__ """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): # real signature unknown; restored from __doc__ """ x.__rtruediv__(y) <==> y/x """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass def __sub__(self, y): # real signature unknown; restored from __doc__ """ x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): # real signature unknown; restored from __doc__ """ x.__truediv__(y) <==> x/y """ pass imag = property(lambda self: 0.0) """the imaginary part of a complex number :type: float """ real = property(lambda self: 0.0) """the real part of a complex number :type: float """
创建一个值为real + imag * j的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数;
- 参数real: int, long, float或字符串;
- 参数imag: int, long, float;
例如:
>>> complex(1, 2)
(1 + 2j)
#数字
>>> complex(1)
(1 + 0j)
#当做字符串处理
>>> complex("1")
(1 + 0j)
#注:这个地方在“+”号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错
>>> complex("1+2j")
(1 + 2j)
18、delattr函数说明
def delattr(p_object, name): # real signature unknown; restored from __doc__ """ delattr(object, name) Delete a named attribute on an object; delattr(x, 'y') is equivalent to ``del x.y''. """ pass
删除object对象名为name的属性;
- 参数object:对象。
- 参数name:属性名称字符串。
例如:
>>> class Person:
... def __init__(self, name, age):
... self.name = name
... self.age = age
...
>>> tom = Person("Tom", 35)
>>> dir(tom)
['__doc__', '__init__', '__module__', 'age', 'name']
>>> delattr(tom, "age")
>>> dir(tom)
['__doc__', '__init__', '__module__', 'name']
19、dict函数说明
20、dir函数说明
def dir(p_object=None): # real signature unknown; restored from __doc__ """ dir([object]) -> list of strings If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. If the object supplies a method named __dir__, it will be used; otherwise the default dir() logic is used and returns: for a module object: the module's attributes. for a class object: its attributes, and recursively the attributes of its bases. for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes. """ return []
不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息; 其中参数object为对象、变量、类型;
例如:
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> import struct
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'struct']
>>> dir(struct)
['Struct', '__builtins__', '__doc__', '__file__', '__name__','__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack','unpack_from']
>>> class Person(object):
... def __dir__(self):
... return ["name", "age", "country"]
...
>>> dir(Person)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__','__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__','__reduce__','__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__','__subclasshook__', '__weakref__']
>>> tom = Person()
>>> dir(tom)
['age', 'country', 'name']
21、divmod函数说明
def divmod(x, y): # known case of __builtin__.divmod """ divmod(x, y) -> (quotient, remainder) Return the tuple (x//y, x%y). Invariant: div*y + mod == x. """ return (0, 0)
divmod(a,b)方法返回的是a//b(除法取整)以及a对b的余数;
返回结果类型为tuple,参数a,b可以为数字(包括复数);
对整数而言,返回值与a/b和a%b相同。如果给出的参数值是浮点数,则结果就是(q,a%b),其中:q通常是math.floor(a/b),但是也可能比这小1,不管在什么情况下,q*b+a%b都非常逼近a;
如果a%b是个非零值,则其正负号与b相同,并且有0<=abs(a%b)<abs(b)成立;
例如:
>>> divmod(9,2)
(4, 1)
>>> divmod(11,3)
(3, 2)
>>> divmod(1+2j,1+0.5j)
((1+0j), 1.5j)
22、enumerate函数说明
class enumerate(object): """ enumerate(iterable[, start]) -> iterator for index, value of iterable Return an enumerate object. iterable must be another object that supports iteration. The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument. enumerate is useful for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ... """ def next(self): # real signature unknown; restored from __doc__ """ x.next() -> the next value, or raise StopIteration """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __init__(self, iterable, start=0): # known special case of enumerate.__init__ """ x.__init__(...) initializes x; see help(type(x)) for signature """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass
enumerate在字典上是枚举、列举的意思,对于一个可迭代的(iterable)或可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值,enumerate多用于在for循环中得到计数;
例如:
>>> 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')]
23、eval函数说明
def eval(source, globals=None, locals=None): # real signature unknown; restored from __doc__ """ eval(source[, globals[, locals]]) -> value Evaluate the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it. """ pass
将字符串str当成有效的表达式来求值并返回计算结果。结合math函数可实现计算器功能;
参数expression,一个Python表达式或函数compile()返回的代码对象;
参数globals,可选,必须是dictionary;
参数locals,可选,任意map对象;
例如:
#字符串转换成列表
>>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>>type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
>>> type(b)
<type 'list'>
#字符串转换成字典
>>> a = "{1: 'a', 2: 'b'}"
>>> type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
{1: 'a', 2: 'b'}
>>> type(b)
<type 'dict'>
#字符串转换成元组
>>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
>>> type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
>>> type(b)
<type 'tuple'>
24、exec函数说明
def exec(*args, **kwargs): # real signature unknown """ Execute the given source in the context of globals and locals. The source may be a string representing one or more Python statements or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it. """ pass
Python3新增函数
用来执行储存在字符串或文件中的Python语句;例如,我们可以在运行时生成一个包含Python代码的字符串,然后使用exec语句执行这些语句;
注:exec语句的用法和eval(),execfile()是不一样的,exec是一个语句(就象print或while),而eval()和execfile()则是内建函数;
例如:
>>> exec 'print "Hello World"'
Hello World
25、execfile函数说明
def execfile(filename, globals=None, locals=None): # real signature unknown; restored from __doc__ """ execfile(filename[, globals[, locals]]) Read and execute a Python script from a file. The globals and locals are dictionaries, defaulting to the current globals and locals. If only globals is given, locals defaults to it. """ pass
python2特有函数
execfile()函数与exec语句等价;
不同之处在于,execfile()函数执行文件中的语句,而exec语句处理字符串。其中globals和locals参数应是字典,该字典包含文件在执行期间有效的符号表;
如果locals参数省略,则所有的引用都使用globals名称空间。如果两个可选参数都省略,文件就访问运行期间的当前符号表;
26、file函数说明
class file(object): """ file(name[, mode[, buffering]]) -> file object Open a file. The mode can be 'r', 'w' or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist when opened for writing or appending; it will be truncated when opened for writing. Add a 'b' to the mode for binary files. Add a '+' to the mode to allow simultaneous reading and writing. If the buffering argument is given, 0 means unbuffered, 1 means line buffered, and larger numbers specify the buffer size. The preferred way to open a file is with the builtin open() function. Add a 'U' to mode to open the file for input with universal newline support. Any line ending in the input file will be seen as a '\n' in Python. Also, a file so opened gains the attribute 'newlines'; the value for this attribute is one of None (no newline read yet), '\r', '\n', '\r\n' or a tuple containing all the newline types seen. 'U' cannot be combined with 'w' or '+' mode. """ def close(self): # real signature unknown; restored from __doc__ """ close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for further I/O operations. close() may be called more than once without error. Some kinds of file objects (for example, opened by popen()) may return an exit status upon closing. """ pass def fileno(self): # real signature unknown; restored from __doc__ """ fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read(). """ return 0 def flush(self): # real signature unknown; restored from __doc__ """ flush() -> None. Flush the internal I/O buffer. """ pass def isatty(self): # real signature unknown; restored from __doc__ """ isatty() -> true or false. True if the file is connected to a tty device. """ return False def next(self): # real signature unknown; restored from __doc__ """ x.next() -> the next value, or raise StopIteration """ pass def read(self, size=None): # real signature unknown; restored from __doc__ """ read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. """ pass def readinto(self): # real signature unknown; restored from __doc__ """ readinto() -> Undocumented. Don't use this; it may go away. """ pass def readline(self, size=None): # real signature unknown; restored from __doc__ """ readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. """ pass def readlines(self, size=None): # real signature unknown; restored from __doc__ """ readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned. """ return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__ """ seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to 0 (offset from start of file, offset should be >= 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable. """ pass def tell(self): # real signature unknown; restored from __doc__ """ tell() -> current file position, an integer (may be a long integer). """ pass def truncate(self, size=None): # real signature unknown; restored from __doc__ """ truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell(). """ pass def write(self, p_str): # real signature unknown; restored from __doc__ """ write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written. """ pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__ """ writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string. """ pass def xreadlines(self): # real signature unknown; restored from __doc__ """ xreadlines() -> returns self. For backward compatibility. File objects now include the performance optimizations previously implemented in the xreadlines module. """ pass def __delattr__(self, name): # real signature unknown; restored from __doc__ """ x.__delattr__('name') <==> del x.name """ pass def __enter__(self): # real signature unknown; restored from __doc__ """ __enter__() -> self. """ return self def __exit__(self, *excinfo): # real signature unknown; restored from __doc__ """ __exit__(*excinfo) -> None. Closes the file. """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __init__(self, name, mode=None, buffering=None): # real signature unknown; restored from __doc__ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setattr__(self, name, value): # real signature unknown; restored from __doc__ """ x.__setattr__('name', value) <==> x.name = value """ pass closed = property(lambda self: True) """True if the file is closed :type: bool """ encoding = property(lambda self: '') """file encoding :type: string """ errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """Unicode error handler""" mode = property(lambda self: '') """file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added) :type: string """ name = property(lambda self: '') """file name :type: string """ newlines = property(lambda self: '') """end-of-line convention used in this file :type: string """ softspace = property(lambda self: True) """flag indicating that a space needs to be printed; used by print :type: bool """
python2特有函数
文件类型的构造函数,等价于open();打开文件时,最好使用open(),而不是直接调用此构造函数,文件更适合于类型测试;
27、filter函数说明
def filter(function_or_none, sequence): # known special case of filter """ filter(function or None, sequence) -> list, tuple, or string Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list. """ pass
根据function参数返回的结果是否为真(true)来过滤list参数中的项,最后返回一个新列表;
如果function参数值为None,就是用identity函数,list参数中的所有为假(false)的元素都被删除;
例如:
>>> a=[1,2,3, 4, 5,6,,7,8,9]
>>> b=filter(lambda x:x>6,a)
>>> print b
[7,8,9]
28、flaot函数说明
29、format函数说明
def format(value, format_spec=None): # real signature unknown; restored from __doc__ """ format(value[, format_spec]) -> string Returns value.__format__(format_spec) format_spec defaults to "" """ return ""
将值格式化为字符串,与以前的"%"操作符相似。用"{}"和":"代替了以前的"%."符号;
例如:
通过位置匹配参数
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
#仅python2.7以上支持
>>> '{}, {}, {}'.format('a', 'b', 'c')
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
#解包参数序列
>>> '{2}, {1}, {0}'.format(*'abc')
'c, b, a'
#参数的索引可以重复
>>> '{0}{1}{0}'.format('abra', 'cad')
'abracadabra'
注意:{}占位符只有在Python2.7+有效,不能为空。
从上面例子可以看到,{}可以为空(Python2.7+),也可以手动指定数序,同一个序号可以重复出现,可以不按顺序指定;
通过名称匹配参数
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
通过属性匹配参数
>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
... 'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __str__(self):
... return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'
通过下标匹配参数
>>> coord = (3, 5)
>>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
'X: 3; Y: 5'
可以指定转化
>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"
字符串对齐并且指定对齐宽度
>>> '{:<30}'.format('left aligned')
'left aligned '
>>> '{:>30}'.format('right aligned')
' right aligned'
>>> '{:^30}'.format('centered')
' centered '
>>> '{:*^30}'.format('centered') # use '*' as a fill char
'***********centered***********'
指定符号显示
>>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'
指定进制
# format also supports binary numbers>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
# with 0x, 0o, or 0b as prefix:
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
使用","作用千位分隔符
>>> '{:,}'.format(1234567890)
'1,234,567,890'
百分数显示
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'
时间格式处理
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'
占位符嵌套
>>> for align, text in zip('<^>', ['left', 'center', 'right']):
... '{0:{fill}{align}16}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>>
>>> octets = [192, 168, 0, 1]
>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
'C0A80001'
>>> int(_, 16)
235521
>>>
>>> width = 5、
>> for num in range(5,12):
... for base in 'dXob':
... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
... print()
...
5 5 101
6 6 110
7 7 111
8 10 1000
9 11 1001
A 12 1010
B 13 1011
30、frozenset函数说明
class frozenset(object): """ frozenset() -> empty frozenset object frozenset(iterable) -> frozenset object Build an immutable unordered collection of unique elements. """ def copy(self, *args, **kwargs): # real signature unknown """ Return a shallow copy of a set. """ pass def difference(self, *args, **kwargs): # real signature unknown """ Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.) """ pass def intersection(self, *args, **kwargs): # real signature unknown """ Return the intersection of two or more sets as a new set. (i.e. elements that are common to all of the sets.) """ pass def isdisjoint(self, *args, **kwargs): # real signature unknown """ Return True if two sets have a null intersection. """ pass def issubset(self, *args, **kwargs): # real signature unknown """ Report whether another set contains this set. """ pass def issuperset(self, *args, **kwargs): # real signature unknown """ Report whether this set contains another set. """ pass def symmetric_difference(self, *args, **kwargs): # real signature unknown """ Return the symmetric difference of two sets as a new set. (i.e. all elements that are in exactly one of the sets.) """ pass def union(self, *args, **kwargs): # real signature unknown """ Return the union of sets as a new set. (i.e. all elements that are in either set.) """ pass def __and__(self, y): # real signature unknown; restored from __doc__ """ x.__and__(y) <==> x&y """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x. """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, seq=()): # known special case of frozenset.__init__ """ x.__init__(...) initializes x; see help(type(x)) for signature """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> xa new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __or__(self, y): # real signature unknown; restored from __doc__ """ x.__or__(y) <==> x|y """ pass def __rand__(self, y): # real signature unknown; restored from __doc__ """ x.__rand__(y) <==> y&x """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ Return state information for pickling. """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __ror__(self, y): # real signature unknown; restored from __doc__ """ x.__ror__(y) <==> y|x """ pass def __rsub__(self, y): # real signature unknown; restored from __doc__ """ x.__rsub__(y) <==> y-x """ pass def __rxor__(self, y): # real signature unknown; restored from __doc__ """ x.__rxor__(y) <==> y^x """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __sub__(self, y): # real signature unknown; restored from __doc__ """ x.__sub__(y) <==> x-y """ pass def __xor__(self, y): # real signature unknown; restored from __doc__ """ x.__xor__(y) <==> x^y """ pass
本函数是返回一个冻结的集合。所谓冻结就是这个集合不能再添加或删除任何集合里的元素。因此与集合set的区别,就是set是可以添加或删除元素,而frozenset不行。frozenset的主要作用就是速度快,它是使用hash算法实现。参数iterable是表示可迭代的对象,比如列表、字典、元组等等。
例如:
>>> l = [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9]
>>> print(len(l), l)
(11, [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9])
>>> set = frozenset(l)
>>> print(len(set), set)
(9, frozenset([1, 2, 3, 4, 5, 6, 7, 8, 9]))
31、getattr函数说明
def getattr(object, name, default=None): # known special case of getattr """ getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. """ pass
getattr()这个方法最主要的作用是实现反射机制。也就是说可以通过字符串获取方法实例。这样,你就可以把一个类可能要调用的方法放在配置文件里,在需要的时候动态加载;
32、globals函数说明
def globals(): # real signature unknown; restored from __doc__ """ globals() -> dictionary Return the dictionary containing the current scope's global variables. """ return {}
返回当前全局符号表,通常在是返回当前模块下的全局符号表,比如全局内建的函数,以及模块里的全局符号(定义声明的变量,类, 实例等);
在函数或者类方法中,globals()返回的模块符号表是其所在模块, 而不是调用模块;
33、hasattr函数说明
def hasattr(p_object, name): # real signature unknown; restored from __doc__ """ hasattr(object, name) -> bool Return whether the object has an attribute with the given name. (This is done by calling getattr(object, name) and catching exceptions.) """ return False
本函数是用来判断对象object的属性(name表示)是否存在。如果属性(name表示)存在,则返回True,否则返回False。参数object是一个对象,参数name是一个属性的字符串表示;
例如:
>>> class Foo:
... def __init__(self):
... self.x = 123
... def test(x):
... self.x = x
...
>>> foo = Foo()
>>> print(hasattr(foo, 'x'))
True
>>> print(hasattr(foo, 'y'))
False
>>> print(hasattr(foo, 'test'))
True
34、hash函数说明
def hash(p_object): # real signature unknown; restored from __doc__ """ hash(object) -> integer Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely. """ return 0
本函数返回对象的哈希值。返回的哈希值是使用一个整数表示,通常使用在字典里,以便实现快速查询键值;
参数object输入是数字类型时,是根据数值来计算的,比如1和1.0计算出来是一样的哈希值,因此说这个函数是不区分不同的数值类型;
例如:
>>> print(hash('abc'))
700737775
>>> print(hash(2.0))
2
>>> print(hash(2))
2
35、help函数说明
def help(with_a_twist): # real signature unknown; restored from __doc__ """ Define the builtin 'help'. This is a wrapper around pydoc.help (with a twist). """ pass
在使用python来编写代码时,会经常使用python 调用函数自带函数或模块,一些不常用的函数或是模块的用途不是很清楚,这时候就需要用到help函数来查看帮助;
这里要注意下,help()函数是查看函数或模块用途的详细说明,而dir()函数是查看函数或模块内的操作方法都有什么,输出的是方法列表;
例如:
#查看一个模块的帮助,之后它回打开这个模块的帮助文档
>>> help('sys')
#查看一个数据类型的帮助
>>> help('str')
#返回字符串的方法及详细说明,这时help(a)则会打开list的操作方法
>>> a = [1,2,3]
>>> help(a)
#显示list的append方法的帮助
>>> help(a.append)
36、hex函数说明
def hex(number): # real signature unknown; restored from __doc__ """ hex(number) -> string Return the hexadecimal representation of an integer or long integer. """ return ""
转换一个整数对象为十六进制的字符串表示,比如像0x的格式。如果对象不是一个整数,应定义一个方法__index__()返回整数;
如果想把本函数的结果转换为整数类型,需要int()函数,并且使用基数为16的方式转换;
另浮点数转换为十六进制表示需要使用float.hex()来转换,而不能使用本函数;
例如:
>>> print(hex(20))
0x14
>>> print(hex(128))
0x80
>>> print(hex(0x55))
0x55
>>> print(hex(-127))
-0x7f
37、id函数说明
def id(p_object): # real signature unknown; restored from __doc__ """ id(object) -> integer Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.) """ return 0
返回的是对象的“身份证号”,唯一且不变,但在不重合的生命周期里,可能会出现相同的id值。此处所说的对象应该特指复合类型的对象(如类、list等),对于字符串、整数等类型,变量的id是随值的改变而改变的。
注:一个对象的id值在CPython解释器里就代表它在内存中的地址(Python的c语言实现的解释器);
例如:
class Obj(): def __init__(self,arg): self.x=arg if __name__ == '__main__': obj=Obj(1) print id(obj) #32754432 obj.x=2 print id(obj) #32754432 s="abc" print id(s) #140190448953184 s="bcd" print id(s) #32809848 x=1 print id(x) #15760488 x=2 print id(x) #15760464
注:用is判断两个对象是否相等时,依据就是这个id值,is与==的区别就是,is是内存中的比较,而==是值的比较;
38、input函数说明
def input(prompt=None): # real signature unknown; restored from __doc__ """ input([prompt]) -> value Equivalent to eval(raw_input(prompt)). """ pass
实现从控制台输入一行字符串。其中参数prompt是输入字符串的提示字符串;
注:与raw_input()相比,这两个函数均能接收字符串 ,但raw_input()直接读取控制台的输入(任何类型的输入它都可以接收)。而对于input(),它希望能够读取一个合法的python表达式,即你输入字符串的时候必须使用引号将它括起来,否则它会引发一个 SyntaxError;
例如:
>>> s = input('#')
#this is the best one
>>> s
'this is the best one'
>>> s = input('#')
#中国是一个国家
>>> s
'中国是一个国家'
def input(*args, **kwargs): # real signature unknown """ Read a string from standard input. The trailing newline is stripped. The prompt string, if given, is printed to standard output without a trailing newline before reading input. If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError. On *nix systems, readline is used if available. """ pass
在python3中input函数等价于python2的raw_input函数;
39、int函数说明
40、intern函数说明
python2特有但非通用函数
def intern(string): # real signature unknown; restored from __doc__ """ intern(string) -> string ``Intern'' the given string. This enters the string in the (global) table of interned strings whose purpose is to speed up dictionary lookups. Return the string itself or the previously interned string object with the same value. """ return ""
将string加入到保留字符串的表,返回值为保留的版本号。“保留字符串”通过指针可用,而不是一个纯的字符串;因此允许利用指针比较代替字符串比较来进行字典关键字的查找,这比通常的字符串比较方法功能有所改善;
在python名称空间表和用于保留模块、类或实力属性的字典中使用的名字通常被保留用以加速脚本执行;
保留字符串定义后不能被作为无用单元收集,所以必须注意在大字典关键字集上使用保留字符串将大大增加内存需求,即使字典关键字应急超出了作用域;
41、isinstance函数说明
def isinstance(p_object, class_or_type_or_tuple): # real signature unknown; restored from __doc__ """ isinstance(object, class-or-type-or-tuple) -> bool Return whether an object is an instance of a class or of a subclass thereof. With a type as second argument, return whether that is the object's type. The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for isinstance(x, A) or isinstance(x, B) or ... (etc.). """ return False
用来判断对象实例object是否是类classinfo的实例,如果是就返回True,否则返回False;参数classinfo可以是类型,也可以是tuple/dict/list等类型;
例如:
>>> class FooA:
... pass
>>> class FooB(FooA):
... pass
>>> class FooC:
... pass
>>> a = FooA()
>>> b = FooB()
>>> c = FooC()
>>> print(isinstance(a, FooA))
True
>>> print(isinstance(a, FooB))
False
>>> print(isinstance(b, FooA))
True
>>> print(isinstance(b, FooB))
True
>>> print(isinstance(c, FooA))
False
>>> print(isinstance(c, FooB))
False
>>> print(isinstance([], list))
True
42、issubclass函数说明
def issubclass(C, B): # real signature unknown; restored from __doc__ """ issubclass(C, B) -> bool Return whether class C is a subclass (i.e., a derived class) of class B. When using a tuple as the second argument issubclass(X, (A, B, ...)), is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.). """ return False
用来判断类参数class是否是类型参数classinfo的子类;
例如:
>>> class Line:
... pass
>>> class RedLine(Line):
... pass
...
>>> class Rect:
... pass
...
>>> print(issubclass(RedLine, Line))True
>>> print(issubclass(Rect, Line))
False
43、iter函数说明
def iter(source, sentinel=None): # known special case of iter """ iter(collection) -> iterator iter(callable, sentinel) -> iterator Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence. In the second form, the callable is called until it returns the sentinel. """ pass
返回一个迭代子对象;
当第二个参数不出现时,参数object应是一个容器,支持迭代协议,也就是有定义有__iter__()函数,或者支持序列访问协议,也就是定义有__getitem__()函数的对象,否则会返回TypeError异常;
当第二个参数哨兵出现时,参数object应是一个可调用对象,定义了__next__()函数,当枚举到的值等于哨兵时,就会抛出异常StopIteration;
例如:
#s是一个iterable对象,它有__getitem__()方法
>>> s = '中国是个国家'
#it是一个iterator对象,它有__next__()和__iter__()方法
>>> it = iter(s)
>>> print(s)
中国是个国家
>>> print(it.__next__())
中
>>> print(it.__next__())
国
>>> print(it.__next__())
是
>>> print(it.__next__())
个
>>> print(it.__next__())
国
>>> print(it.__next__())
家
44、len函数说明
def len(p_object): # real signature unknown; restored from __doc__ """ len(object) -> integer Return the number of items of a sequence or collection. """ return 0
返回对象s的长度,所谓的长度是指容器类的数据项个数,比如字符串、元组、列表、字典等;
例如:
>>> s1 = '123456789'
>>> s2 = '国家'
>>> print(s, ': ', len(s1))
123456789 : 9
>>> print(soft, ': ', len(s2))
国家 : 2
>>> l = [2,3,4,5]
>>> print(l, ': ', len(l))
[2, 3, 4, 5] : 4
>>> d = {2 : 'two', 3 : 'three' }
>>> print(d, ': ', len(d))
{2: 'two', 3: 'three'} : 2
45、list函数说明
46、locals函数说明
def locals(): # real signature unknown; restored from __doc__ """ locals() -> dictionary Update and return a dictionary containing the current scope's local variables. """ return {}
更新并以字典形式返回当前局部符号表; 自由变量由函数块的locals()返回,而不会由class块来返回;需要注意的是locals()字典不应该被修改;在解释器中对修改行为可能对local值或者自由变量无效;
47、long函数说明
python2特有函数
48、map函数说明
def map(function, sequence, *sequence_1): # real signature unknown; restored from __doc__ """ map(function, sequence[, sequence, ...]) -> list Return a list of the results of applying the function to the items of the argument sequence(s). If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length. If the function is None, return a list of the items of the sequence (or a list of tuples if more than one sequence). """ return []
把函数对象function作为函数,iterable对象的每一项作为参数,然后进行计算后输出迭代子iterator;
如果函数对象function可以输入多参数,那么后面可以跟多个可迭代的对象。多个迭代对象时,以最短的对象为运行结果的判断;
例如:
>>> x = range(10)
>>> print(list(map(hex, x)))
['0x0', '0x1', '0x2', '0x3', '0x4', '0x5', '0x6', '0x7', '0x8', '0x9']
>>> print(list(map(lambda y : y * 2 + 1, x)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> print(list(map(lambda y, z : y * 2 + z, x, x)))
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
49、max函数说明
def max(*args, **kwargs): # known special case of max """ max(iterable[, key=func]) -> value max(a, b, c, ...[, key=func]) -> value With a single iterable argument, return its largest item. With two or more arguments, return the largest argument. """ pass
迭代对象iterable进行比较,找出最大值返回。当key参数不为空时,就以key的函数对象为判断的标准;
例如:
>>> array1 = range(10)
>>> array2 = range(0, 20, 3)
>>> print('max(array1)=', max(array1))
max(array1)= 9
>>> print('max(array2)=', max(array2))
max(array2)= 18
>>> print('max(array1,)=', max(array1, key=lambda x: x > 3) )
max(array1,)= 4
>>> print(max(1, 2))
2
>>> print(max('ah', 'bf', key=lambda x: x[1]))
ah
>>> print(max(array1, array2, key=lambda x: x[1]))
range(0, 20, 3)
>>> def comparator(x):
... return x[2]
>>> print(max('ah2', 'bf3', key=comparator))
bf3
50、memoryview函数说明
class memoryview(object): """ memoryview(object) Create a new memoryview object which references the given object. """ def tobytes(self, *args, **kwargs): # real signature unknown pass def tolist(self, *args, **kwargs): # real signature unknown pass def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __init__(self, p_object): # real signature unknown; restored from __doc__ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> xa new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass format = property(lambda self: object(), lambda self, v: None, lambda self: None) # default itemsize = property(lambda self: object(), lambda self, v: None, lambda self: None) # default ndim = property(lambda self: object(), lambda self, v: None, lambda self: None) # default readonly = property(lambda self: object(), lambda self, v: None, lambda self: None) # default shape = property(lambda self: object(), lambda self, v: None, lambda self: None) # default strides = property(lambda self: object(), lambda self, v: None, lambda self: None) # default suboffsets = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
返回对象obj的内存查看对象,所谓内存查看对象,就是对象符合缓冲区协议的对象,为了给别的代码使用缓冲区里的数据,而不必拷贝,就可以直接使用;
例如:
>>> v = memoryview(b'abc123')
>>> print(v[1])
98
>>> print(v[0])
97
>>> import struct
>>> buf = struct.pack("i"*12, *list(range(12)))
>>> x = memoryview(buf)
>>> y = x.cast('i', shape=[2,2,3])
>>> print(y.tolist())
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
51、min函数说明
def min(*args, **kwargs): # known special case of min """ min(iterable[, key=func]) -> value min(a, b, c, ...[, key=func]) -> value With a single iterable argument, return its smallest item. With two or more arguments, return the smallest argument. """ pass
迭代对象iterable进行比较,找出最小值返回。当key参数不为空时,就以key的函数对象为判断的标准;
52、next函数说明
def next(iterator, default=None): # real signature unknown; restored from __doc__ """ next(iterator[, default]) Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration. """ pass
返回迭代子下一个元素的值,主要通过调用__next__()方法来实现的。如果default参数有设置,当下一个元素不存在时,就返回default参数的值,否则抛出异常StopIteration;
例如:
>>> l = [1, 3, 4]
>>> it = iter(l)
>>> print(next(it))
1
>>> print(next(it, 1))
3
>>> print(next(it, 1))
4
>>> print(next(it, 1))
1
>>> print(next(it, 1))
1
53、object函数说明
class object: """ The most base type """ def __delattr__(self, name): # real signature unknown; restored from __doc__ """ x.__delattr__('name') <==> del x.name """ pass def __format__(self, *args, **kwargs): # real signature unknown """ default object formatter """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self): # known special case of object.__init__ """ x.__init__(...) initializes x; see help(type(x)) for signature """ pass @staticmethod # known case of __new__ def __new__(cls, *more): # known special case of object.__new__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __reduce_ex__(self, *args, **kwargs): # real signature unknown """ helper for pickle """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ helper for pickle """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setattr__(self, name, value): # real signature unknown; restored from __doc__ """ x.__setattr__('name', value) <==> x.name = value """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ __sizeof__() -> int size of object in memory, in bytes """ return 0 def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass @classmethod # known case def __subclasshook__(cls, subclass): # known special case of object.__subclasshook__ """ Abstract classes can override this to customize issubclass(). This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached). """ pass __class__ = None # (!) forward: type, real value is '' __dict__ = {} __doc__ = '' __module__ = ''
返回一个无新特征的对象。这个对象是所有基类的对象,但要注意的是这个对象实例不能添加属性给它,因为它没有__dict__属性。
例如:
>>> a = object()
>>> b = object()
>>> print(a == b)
False
>>> print(a is b)
False
54、oct函数说明
def oct(number): # real signature unknown; restored from __doc__ """ oct(number) -> string Return the octal representation of an integer or long integer. """ return ""
转换整数x为八进制表示的字符串。如果对象x不是一个整数,需要这个对象提供__index__()方法来返回一个整数;
55、open函数说明
def open(name, mode=None, buffering=None): # real signature unknown; restored from __doc__ """ open(name[, mode[, buffering]]) -> file object Open a file using the file() type, returns a file object. This is the preferred way to open a file. See file.__doc__ for further information. """ return file('/dev/null')open
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open """ Open file and return a stream. Raise IOError upon failure. file is either a text or byte string giving the name (and the path if the file isn't in the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.) mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for creating and writing to a new file, and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are: ========= =============================================================== Character Meaning --------- --------------------------------------------------------------- 'r' open for reading (default) 'w' open for writing, truncating the file first 'x' create a new file and open it for writing 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newline mode (deprecated) ========= =============================================================== The default mode is 'rt' (open for reading text). For binary random access, the mode 'w+b' opens and truncates the file to 0 bytes, while 'r+b' opens the file without truncation. The 'x' mode implies 'w' and raises an `FileExistsError` if the file already exists. Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn't. Files opened in binary mode (appending 'b' to the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is appended to the mode argument), the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given. 'U' mode is deprecated and will raise an exception in future versions of Python. It has no effect in Python 3. Use newline to control universal newlines mode. buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows: * Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device's "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`. On many systems, the buffer will typically be 4096 or 8192 bytes long. * "Interactive" text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files. encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings. errors is an optional string that specifies how encoding errors are to be handled---this argument should not be used in binary mode. Pass 'strict' to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore errors. (Note that ignoring encoding errors can lead to data loss.) See the documentation for codecs.register or run 'help(codecs.Codec)' for a list of the permitted encoding error strings. newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newline 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. * On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. If closefd is False, the underlying file descriptor will be kept open when the file is closed. This does not work when a file name is given and must be True in that case. 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 (*file*, *flags*). *opener* must return an open file descriptor (passing os.open as *opener* results in functionality similar to passing None). open() returns a file object whose type depends on the mode, and through which the standard file operations such as reading and writing are performed. When open() is used to open a file in a text mode ('w', 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open a file in a binary mode, the returned class varies: in read binary mode, it returns a BufferedReader; in write binary and append binary modes, it returns a BufferedWriter, and in read/write mode, it returns a BufferedRandom. It is also possible to use a string or bytearray as a file for both reading and writing. For strings StringIO can be used like a file opened in a text mode, and for bytes a BytesIO can be used like a file opened in a binary mode. """ pass
打开一个文件并返回文件对象。如果文件不能打开,抛出异常OSError。
参数file是一个字符串表示的文件名称,或者一个数组表示的文件名称。文件名称可以是相对当前目录的路径,也可以是绝对路径表示。
参数mode是指明打开文件的模式。默认值是’r’,表示使用文本的方式打开文件来读取。
- ‘r’表示打开文件只读,不能写。
- ‘w’表示打开文件只写,并且清空文件。
- ‘x’表示独占打开文件,如果文件已经存打开就会失败。
- ‘a’表示打开文件写,不清空文件,在文件后尾追加的方式写入。
- ‘b’表示二进制的模式打开文件。
- ‘t’表示文本模式,默认情况下就是这种模式。
- ‘+’打开文件更新(读取或写入)。
缺省时的模式就相当于’rt’。比如’w+b’就是打开文件进入读写,把文件清空;’r+b’打开文件,但不把文件清空。
参数buffering是一个可选的参数,用来表示缓冲区的策略选择。设置为0时,表示不使用缓冲区,直接读写,仅在二进制模式下有效。设置为1时,表示在文本模式下使用行缓冲区方式。设置为大于1时,表示缓冲区的设置大小。如果参数buffering没有给出,使用默认时,会采用下面策略来选择:
- 对于二进制文件模式时,采用固定块内存缓冲区方式,内存块的大小根据系统设备的分配的磁盘块来决定,如果获取系统磁盘块的大小失败,就使用内部常量io.DEFAULT_BUFFER_SIZE定义的大小。一般的操作系统上,块的大小是4096或者8192字节大小。
- 对于交互的文本文件(采用isatty()判断为True)时,采用一行缓冲区的方式。其它文本文件使用跟二进制一样的方式。
参数encoding是指明对文件编码,仅适用于文本文件。如果不明编码方式,默认是使用locale.getpreferredencoding()函数返回的编码方式。
参数errors是用来指明编码和解码错误时怎么样处理。不能在二进制的模式下使用。
- 当指明为’strict’时,编码出错则抛出异常ValueError。
- 当指明为’ignore’时,忽略错误。
- 当指明为’replace’时,使用某字符进行替代模式,比如使用’?’来替换出错的。
- 其它相应还有surrogateescape/xmlcharrefreplacs/backslashreplace。
参数newline是用来控制文本模式之下,一行的结束字符。可以是None,’’,\n,\r,\r\n等。
当在读取模式下,如果新行符为None,那么就作为通用换行符模式工作,意思就是说当遇到\n,\r或\r\n都可以作为换行标识,并且统一转换为\n作为文本输入的换行符。当设置为空’’时,也是通用换行符模式工作,但不作转换为\n,输入什么样的,就保持原样全输入。当设置为其它相应字符时,就会判断到相应的字符作为换行符,并保持原样输入到文本。
当在输出模式时,如果新行符为None,那么所有输出文本都是采用\n作为换行符。如果设置为’’或者\n时,不作任何的替换动作。如果是其它字符,会在字符后面添加\n作为换行符。
参数closefd是用来当给一个文件句柄传进来时,而当退出文件使用时,而不对文件句柄进行关闭。如果传递一个文件名进来,这个参数无效,必定为True方式。
参数opener是用来实现自己定义打开文件方式。
56、ord函数说明
def ord(c): # real signature unknown; restored from __doc__ """ ord(c) -> integer Return the integer ordinal of a one-character string. """ return 0
把一个字符串表示的字符转换为字符相对应的整数,适用于UNICODE字符;比如ord(‘a’)则返回整数97,ord(‘\u2020’)则返回整数8224;与函数chr()的功能刚好相反;
例如:
>>> print('ord(a)', ord('a'))
ord(a) 97
>>> print('ord(u2020)', ord('\u2020'))
ord(u2020) 8224
>>> print('ord(1)', ord('1'))
ord(1) 49
57、pow函数说明
def pow(x, y, z=None): # real signature unknown; restored from __doc__ """ pow(x, y[, z]) -> number With two arguments, equivalent to x**y. With three arguments, equivalent to (x**y) % z, but may be more efficient (e.g. for longs). """ return 0
计算x的y次方,如果z在存在,则再对结果进行取模,其结果等效于pow(x,y) %z;其中pow(x, y)与x**y等效;采用一起计算的方式是为了提高计算的效率,要求三个参数必须为数值类型;
例如:
>>> print(pow(2, 2), 2**2)
4 4
>>> print(pow(2, 8), 2**8)256 256
>>> print(pow(2, 8, 3), 2**8 % 3)
1 1
>>> print(pow(2, -8))
0.00390625
58、print函数说明
def print(*args, **kwargs): # known special case of print """ print(value, ..., sep=' ', end='\n', file=sys.stdout) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. """ pass
实现对象以字符串表示的方式格式化输出到流文件对象file里;
其中所有非关键字参数都按str()方式进行转换为字符串输出,关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分隔字符;
关键字参数end是输出结束时的字符,默认是换行符\n;
关键字参数file是定义流输出的文件,可以是标准的系统输出sys.stdout,也可以重定义为别的文件;
参数flush是立即把内容输出到流文件,不作缓存;
python2支持print ''及print()两种格式;
例如:
>>> print 'How Are You!'
How Are You!
>>> print ('How Are You!')
How Are You!
python3仅支持print()格式;
例如:
>>> print ('How Are You!')
How Are You!
>>> print 'How Are You!'File "<stdin>", line 1
print 'How Are You!'
^
SyntaxError: Missing parentheses in call to 'print'
59、property函数说明
class property(object): """ property(fget=None, fset=None, fdel=None, doc=None) -> property attribute fget is a function to be used for getting an attribute value, and likewise fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x: class C(object): 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.") Decorators make defining new properties or modifying existing ones easy: class C(object): @property def x(self): "I am the 'x' property." return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x """ def deleter(self, *args, **kwargs): # real signature unknown """ Descriptor to change the deleter on a property. """ pass def getter(self, *args, **kwargs): # real signature unknown """ Descriptor to change the getter on a property. """ pass def setter(self, *args, **kwargs): # real signature unknown """ Descriptor to change the setter on a property. """ pass def __delete__(self, obj): # real signature unknown; restored from __doc__ """ descr.__delete__(obj) """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __get__(self, obj, type=None): # real signature unknown; restored from __doc__ """ descr.__get__(obj[, type]) -> value """ pass def __init__(self, fget=None, fset=None, fdel=None, doc=None): # known special case of property.__init__ """ property(fget=None, fset=None, fdel=None, doc=None) -> property attribute fget is a function to be used for getting an attribute value, and likewise fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x: class C(object): 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.") Decorators make defining new properties or modifying existing ones easy: class C(object): @property def x(self): "I am the 'x' property." return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x # (copied from class doc) """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __set__(self, obj, value): # real signature unknown; restored from __doc__ """ descr.__set__(obj, value) """ pass fdel = property(lambda self: object(), lambda self, v: None, lambda self: None) # default fget = property(lambda self: object(), lambda self, v: None, lambda self: None) # default fset = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
设置类成员的属性。参数fget是获取类成员的属性值;参数fset是设置类成员的属性值;fdel是删除类成员;参数doc是设置属性的文档字符串。通过这个函数的方式,可以实现类成员变量隐藏的方式,也就是面向对象里封装的要求;
例如:
class Foo: 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.") foo = Foo() foo.x = 2000 print(foo.x) del foo.x
60、range函数说明
def range(start=None, stop=None, step=None): # known special case of range """ range(stop) -> list of integers range(start, stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. """ pass
随机函数,根据start与stop指定的范围以及step设定的步长,生成一个序列;
例如:
>>> range(5)
[0, 1, 2, 3, 4]
>>> range(1,5)
[1, 2, 3, 4]
>>> range(0,6,2)
[0, 2, 4]
61、raw_input函数说明
python2特有函数
def raw_input(prompt=None): # real signature unknown; restored from __doc__ """ raw_input([prompt]) -> string Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading. """ return ""
通过读取控制台的输入与用户实现交互;
注:raw_input() 将所有输入作为字符串看待,返回字符串类型;而 input() 在对待纯数字输入时具有自己的特性,它返回所输入的数字的类型( int, float );
62、reduce函数说明
python2特有函数
def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__ """ reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. """ pass
一个二元操作函数,用来将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给reduce中的函数 func()(必须是一个二元操作函数)先对集合中的第1,2个数据进行操作,得到的结果再与第三个数据用func()函数运算,最后得到一个结果;
即该函数一次应用function(支持两个函数)到sequence中的每个元素上,逐渐缩短整个语句直到为一个单一的值;
注:在python 3以后,reduce已经不在built-in function里了,需通过以下命令加载reduce;
from functools import reduce
例如:
#其结果如同执行以下计算一样:((((1*2)*3)*4)*5)
>>> reduce(lambda x,y:x*y,[1,2,3,4,5])
120
#如果给出initializer参数值,则initializer参数值就被用作序列的第一个元素,如下列所示:
>>> reduce(lambda x,y:x*y,[1,2,3,4,5],10)
1200
63、reload函数说明
python2特有函数
def reload(module): # real signature unknown; restored from __doc__ """ reload(module) -> module Reload the module. The module must have been successfully imported before. """ pass
将以前导入过的模块再加载一次,重新加载(reload)包括最初导入模块是应用的分析过程和初始化过程,这样就允许在不退出解释器的情况重新加载已更改的python模块。
使用reload()函数的若干注意事项如下:
- 如果模块在语法上是正确的,但在初始化过程中失败,则导入过程不能正确地将模块的名字绑定到符号表中,这时,必须在模块能被重新加载之前使用import()函数加载该模块;
- 重新加载的模块不删除最初旧版本在符号表中的登记项。对于有恒定名字的对象和函数,这不是问题;但是,若对一模块实体更改了名字,模块名在重新加载后仍保持在符号表中;
- 支持扩展模块(它依赖与内置的或所支持的动态加载的函数库)的重新加载,但可能是无目标的,并且确定可能导致失败,这完全依赖于动态加载的函数库的行为;
- 如果以模块利用from…import…方式从另一个模块导入对象,reload()函数不重定义导入的对象,可利用import…形式避免这个问题;
- 提供类的重新加载模块不影响所提供类的任何已存实例——已存实例将继续使用原来的方法定义;只有该类的新实例使用新格式,这个原则对派生类同样适用;
注:在python 3以后,reload已经不在built-in function里了,需通过以下命令加载reduce;
from imp import reload
64、repr函数说明
def repr(p_object): # real signature unknown; restored from __doc__ """ repr(object) -> string Return the canonical string representation of the object. For most object types, eval(repr(object)) == object. """ return ""
返回对象object的详细说明字符串。
例如:
>>> print(repr(range(5)))
range(0, 5)
>>> print(repr(help))
Type help() for interactive help, or help(object) for help about object.
>>> print(repr(0x200))
512
>>> print(repr([2,4,5]))
[2, 4, 5]
65、reversed函数说明
class reversed(object): """ reversed(sequence) -> reverse iterator over values of the sequence Return a reverse iterator """ def next(self): # real signature unknown; restored from __doc__ """ x.next() -> the next value, or raise StopIteration """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __init__(self, sequence): # real signature unknown; restored from __doc__ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __length_hint__(self, *args, **kwargs): # real signature unknown """ Private method returning an estimate of len(list(it)). """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass
返回序列seq的反向访问的迭代子;
例如:
>>> for i in reversed([2, 3, 4, 5]):
... print(i, end = ',')
5,4,3,2,
66、round函数说明
def round(number, ndigits=None): # real signature unknown; restored from __doc__ """ round(number[, ndigits]) -> floating point number Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative. """ return 0.0
实现对浮点数进行四舍五入的计算,参数number是浮点数;参数ndigits是保留几位小数,默认是0值。不过要注意的是转换出来的小数表示可能还是差异,最好使用库专用的数字来计算四舍五入运算。
例如:
>>> print('round(0.5)=', round(0.5), ', round(-0.5)=', round(-0.5))
round(0.5)= 0 , round(-0.5)= 0
>>> print('round(1.1)=', round(1.1), ', round(-1.1)=', round(-1.1))
round(1.1)= 1 , round(-1.1)= -1
>>> print('round(1.545666, 2)=', round(1.545666, 2), ', round(-1.545666)=', round(-1.545666))
round(1.545666, 2)= 1.55 , round(-1.545666)= -2
>>> for i in range(10):
... x = 1.0 + 0.1*i
... print(float(x), round(x), sep = ' = ')
1.0 = 1
1.1 = 1
1.2 = 1
1.3 = 1
1.4 = 1
1.5 = 2
1.6 = 2
1.7000000000000002 = 2
1.8 = 2
1.9 = 2
67、set函数说明
68、setattr函数说明
def setattr(p_object, name, value): # real signature unknown; restored from __doc__ """ setattr(object, name, value) Set a named attribute on an object; setattr(x, 'y', v) is equivalent to ``x.y = v''. """ pass
实现增加或设置对象object一个属性名称name,并设置相应的值value。一般情况与getattr()配套使用;
例如:
class Foo: pass foo = Foo() setattr(foo, 'name', 'caijunsheng') print(foo.name)
69、slice函数说明
class slice(object): """ slice(stop) slice(start, stop[, step]) Create a slice object. This is used for extended slicing (e.g. a[0:10:2]). """ def indices(self, len): # real signature unknown; restored from __doc__ """ S.indices(len) -> (start, stop, stride) Assuming a sequence of length len, calculate the start and stop indices, and the stride length of the extended slice described by S. Out of bounds indices are clipped in a manner consistent with the handling of normal slices. """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, stop): # real signature unknown; restored from __doc__ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ Return state information for pickling. """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass start = property(lambda self: 0) """:type: int""" step = property(lambda self: 0) """:type: int""" stop = property(lambda self: 0) """:type: int"""
实现切片对象,主要用在切片操作函数里的参数传递;
例如:
>>> myslice = slice(5)
>>> print(myslice)
slice(None, 5, None)
>>> l = list(range(10))
>>> print(l[myslice])
[0, 1, 2, 3, 4]
70、sorted函数说明
def sorted(iterable, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__ """ sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list """ pass
实现对可迭代对象iterable进行排序,可选参数key是比较键的函数;reverse是表示是否反向排列对象里的项,是布尔值;
例如:
>>> print(sorted([5, 2, 3, 1, 4]))
[1, 2, 3, 4, 5]
>>> print(sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}, reverse = True))
[5, 4, 3, 2, 1]
>>> print(sorted("This is a test string from Andrew".split(), key=str.lower))
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
71、staticmethod函数说明
class staticmethod(object): """ staticmethod(function) -> method Convert a function to be 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, ...): ... It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see the classmethod builtin. """ def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __get__(self, obj, type=None): # real signature unknown; restored from __doc__ """ descr.__get__(obj[, type]) -> value """ pass def __init__(self, function): # real signature unknown; restored from __doc__ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass __func__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
返回一个静态函数对象,主要用来作为静态函数的修饰符;静态函数的特性是可以直接通过类命名空间访问,也就是说没有定义类实例也可以使用此函数;也可以通过类实例来访问;
例如:
>>> class Foo:
... @staticmethod
... def Add(a, b):
... return a + b
...
>>> print(Foo.Add(2, 8))
10
>>> foo = Foo()
>>> print(foo.Add(3, 7))
10
72、str函数说明
73、sum函数说明
def sum(sequence, start=None): # real signature unknown; restored from __doc__ """ sum(sequence[, start]) -> value Return the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the sequence is empty, return start. """ pass
用来计算可迭代对象iterable的和,然后以这个结果再加上start的值。参数start用来指定相加的参数,如果没有设置这个值,默认是0值。要计算和的序列一般是数字类型,并且开始参数要设置为数字类型。其它有些情况之下,使用别的计算和的方式会更好,比如计算字符串的和使用’’.join(sequence);或者计算浮点数的和使用math.fsum();或者计算多序列的和使用itertools.chain()。
例如:
>>> l = range(10)
>>> print(l, '=', sum(l))
range(0, 10) = 45
>>> print(sum([2, 5, 8], 1))
16
>>> print(sum([2, 5, 8], 2))
17
>>> print(sum((2, 3, 4), 1))
10
>>> print(sum(set([2, 3, 4]), 1))
10
74、super函数说明
class super(object): """ super(type, obj) -> bound super object; requires isinstance(obj, type) super(type) -> unbound super object super(type, type2) -> bound super object; requires issubclass(type2, type) Typical use to call a cooperative superclass method: class C(B): def meth(self, arg): super(C, self).meth(arg) """ def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __get__(self, obj, type=None): # real signature unknown; restored from __doc__ """ descr.__get__(obj[, type]) -> value """ pass def __init__(self, type1, type2=None): # known special case of super.__init__ """ super(type, obj) -> bound super object; requires isinstance(obj, type) super(type) -> unbound super object super(type, type2) -> bound super object; requires issubclass(type2, type) Typical use to call a cooperative superclass method: class C(B): def meth(self, arg): super(C, self).meth(arg) # (copied from class doc) """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass __self_class__ = property(lambda self: type(object)) """the type of the instance invoking super(); may be None :type: type """ __self__ = property(lambda self: type(object)) """the instance invoking super(); may be None :type: type """ __thisclass__ = property(lambda self: type(object)) """the class invoking super() :type: type """
实现访问父类或兄弟类对象,是返回一个代理类对象,以便访问父类或兄弟类的方法;
使用这个函数主要用来避免在继续类时使用基类的类名称,以及多重继承时,保证只调用一次基类的构造函数;
要注意点就是不能与调用基类名称方式混合使用;
例如:
class A: def __init__(self): print('A.init') class B(A): def __init__(self): super().__init__() print('B.init') b = B()
75、tuple函数说明
76、type函数说明
class type(object): """ type(object) -> the object's type type(name, bases, dict) -> a new type """ def mro(self): # real signature unknown; restored from __doc__ """ mro() -> list return a type's method resolution order """ return [] def __call__(self, *more): # real signature unknown; restored from __doc__ """ x.__call__(...) <==> x(...) """ pass def __delattr__(self, name): # real signature unknown; restored from __doc__ """ x.__delattr__('name') <==> del x.name """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(cls, what, bases=None, dict=None): # known special case of type.__init__ """ type(object) -> the object's type type(name, bases, dict) -> a new type # (copied from class doc) """ pass def __instancecheck__(self): # real signature unknown; restored from __doc__ """ __instancecheck__() -> bool check if an object is an instance """ return False def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> xa new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setattr__(self, name, value): # real signature unknown; restored from __doc__ """ x.__setattr__('name', value) <==> x.name = value """ pass def __subclasscheck__(self): # real signature unknown; restored from __doc__ """ __subclasscheck__() -> bool check if a class is a subclass """ return False def __subclasses__(self): # real signature unknown; restored from __doc__ """ __subclasses__() -> list of immediate subclasses """ return [] __abstractmethods__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default __bases__ = ( object, ) __base__ = object __basicsize__ = 872 __dictoffset__ = 264 __dict__ = None # (!) real value is '' __flags__ = -2146544149 __itemsize__ = 40 __mro__ = ( None, # (!) forward: type, real value is '' object, ) __name__ = 'type' __weakrefoffset__ = 368
返回对象的类型对象;
只有一个参数object时,直接返回对象的类型对象。如果只是想判断一个对象是否属于某一个类的对象,可以使用isinstance()函数,并不需要本函数返回类型对象来判断,因为在有继承关系时,它并不返回基类的类型对象;
当有三个参数时,name是类的名称;bases是基类的元组;dict是类内定义的命名空间变量;
例如:
>>> print(type([]))
<class 'list'>
>>> print(type([2]))
<class 'list'>
>>> print(type({0:'zero'}))
<class 'dict'>
>>> class Foo:
... x = 1
... y = 2
...
>>> print(type('Foo', (object, ), dict(x = 1)))<class '__main__.Foo'>
77、unichr函数说明
python2特有函数
def unichr(i): # real signature unknown; restored from __doc__ """ unichr(i) -> Unicode character Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. """ return u""
返回代码是一个整型参数i的Unicode字符的Unicode字符串。此函数等价于前面论述的chr()函数。请注意,要将Unicode字符转换回其整数格式,可使用ord()函数;没有uniord()函数、如果给出的整数超出0~65535这个范围,则引发ValueError异常;
78、unicode函数说明
python2特有函数
class unicode(basestring): """ unicode(object='') -> unicode object unicode(string[, encoding[, errors]]) -> unicode object Create a new Unicode object from the given encoded string. encoding defaults to the current default string encoding. errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'. """ def capitalize(self): # real signature unknown; restored from __doc__ """ S.capitalize() -> unicode Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. """ return u"" def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.center(width[, fillchar]) -> unicode Return S centered in a Unicode string of length width. Padding is done using the specified fill character (default is a space) """ return u"" def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in Unicode string S[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return 0 def decode(self, encoding=None, errors=None): # real signature unknown; restored from __doc__ """ S.decode([encoding[,errors]]) -> string or unicode Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. """ return "" def encode(self, encoding=None, errors=None): # real signature unknown; restored from __doc__ """ S.encode([encoding[,errors]]) -> string or unicode Encodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors. """ return "" def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. """ return False def expandtabs(self, tabsize=None): # real signature unknown; restored from __doc__ """ S.expandtabs([tabsize]) -> unicode Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ return u"" def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def format(self, *args, **kwargs): # known special case of unicode.format """ S.format(*args, **kwargs) -> unicode Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ pass def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.index(sub [,start [,end]]) -> int Like S.find() but raise ValueError when the substring is not found. """ return 0 def isalnum(self): # real signature unknown; restored from __doc__ """ S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise. """ return False def isalpha(self): # real signature unknown; restored from __doc__ """ S.isalpha() -> bool Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise. """ return False def isdecimal(self): # real signature unknown; restored from __doc__ """ S.isdecimal() -> bool Return True if there are only decimal characters in S, False otherwise. """ return False def isdigit(self): # real signature unknown; restored from __doc__ """ S.isdigit() -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise. """ return False def islower(self): # real signature unknown; restored from __doc__ """ S.islower() -> bool Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise. """ return False def isnumeric(self): # real signature unknown; restored from __doc__ """ S.isnumeric() -> bool Return True if there are only numeric characters in S, False otherwise. """ return False def isspace(self): # real signature unknown; restored from __doc__ """ S.isspace() -> bool Return True if all characters in S are whitespace and there is at least one character in S, False otherwise. """ return False def istitle(self): # real signature unknown; restored from __doc__ """ S.istitle() -> bool Return True if S is a titlecased string and there is at least one character in S, i.e. upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. """ return False def isupper(self): # real signature unknown; restored from __doc__ """ S.isupper() -> bool Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise. """ return False def join(self, iterable): # real signature unknown; restored from __doc__ """ S.join(iterable) -> unicode Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. """ return u"" def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.ljust(width[, fillchar]) -> int Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space). """ return 0 def lower(self): # real signature unknown; restored from __doc__ """ S.lower() -> unicode Return a copy of the string S converted to lowercase. """ return u"" def lstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.lstrip([chars]) -> unicode Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is a str, it will be converted to unicode before stripping """ return u"" def partition(self, sep): # real signature unknown; restored from __doc__ """ S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. """ pass def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ """ S.replace(old, new[, count]) -> unicode Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. """ return u"" def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rfind(sub [,start [,end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rindex(sub [,start [,end]]) -> int Like S.rfind() but raise ValueError when the substring is not found. """ return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.rjust(width[, fillchar]) -> unicode Return S right-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space). """ return u"" def rpartition(self, sep): # real signature unknown; restored from __doc__ """ S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S. """ pass def rsplit(self, sep=None, maxsplit=None): # real signature unknown; restored from __doc__ """ S.rsplit([sep [,maxsplit]]) -> list of strings Return a list of the words in S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified, any whitespace string is a separator. """ return [] def rstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.rstrip([chars]) -> unicode Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is a str, it will be converted to unicode before stripping """ return u"" def split(self, sep=None, maxsplit=None): # real signature unknown; restored from __doc__ """ S.split([sep [,maxsplit]]) -> list of strings Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. """ return [] def splitlines(self, keepends=False): # real signature unknown; restored from __doc__ """ S.splitlines(keepends=False) -> list of strings Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ return [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. """ return False def strip(self, chars=None): # real signature unknown; restored from __doc__ """ S.strip([chars]) -> unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is a str, it will be converted to unicode before stripping """ return u"" def swapcase(self): # real signature unknown; restored from __doc__ """ S.swapcase() -> unicode Return a copy of S with uppercase characters converted to lowercase and vice versa. """ return u"" def title(self): # real signature unknown; restored from __doc__ """ S.title() -> unicode Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case. """ return u"" def translate(self, table): # real signature unknown; restored from __doc__ """ S.translate(table) -> unicode Return a copy of the string S, where all characters have been mapped through the given translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted. """ return u"" def upper(self): # real signature unknown; restored from __doc__ """ S.upper() -> unicode Return a copy of S converted to uppercase. """ return u"" def zfill(self, width): # real signature unknown; restored from __doc__ """ S.zfill(width) -> unicode Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. """ return u"" def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown pass def _formatter_parser(self, *args, **kwargs): # real signature unknown pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __format__(self, format_spec): # real signature unknown; restored from __doc__ """ S.__format__(format_spec) -> unicode Return a formatted version of S as described by format_spec. """ return u"" def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, string=u'', encoding=None, errors='strict'): # known special case of unicode.__init__ """ unicode(object='') -> unicode object unicode(string[, encoding[, errors]]) -> unicode object Create a new Unicode object from the given encoded string. encoding defaults to the current default string encoding. errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'. # (copied from class doc) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> xx%y """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass
该函数利用编码格式解码器将给定的字符串从一种格式解码为另一种格式,编码的任何错误都用errors参数定义的字符串标记;
此函数特别用于在字符串和Unicode编码格式之间转换,默认(当不给出encoding参数值)操作是以严格方式将字符串解码为UTF-8格式,发生errors错误时就引发ValueError异常;
79、vars函数说明
def vars(p_object=None): # real signature unknown; restored from __doc__ """ vars([object]) -> dictionary Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__. """ return {}
实现返回对象object的属性和属性值的字典对象;如果默认不输入参数,就打印当前调用位置的属性和属性值,相当于locals()的功能;如果有参数输入,就只打印这个参数相应的属性和属性值;
例如:
print(vars()) class Foo: a = 1 print(vars(Foo)) foo = Foo() print(vars(foo))
80、xrange函数说明
class xrange(object): """ xrange(stop) -> xrange object xrange(start, stop[, step]) -> xrange object Like range(), but instead of returning a list, returns an object that generates the numbers in the range on demand. For looping, this is slightly faster than range() and more memory efficient. """ def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __init__(self, stop): # real signature unknown; restored from __doc__ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __reduce__(self, *args, **kwargs): # real signature unknown pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __reversed__(self, *args, **kwargs): # real signature unknown """ Returns a reverse iterator. """ pass
python2特有函数
用法与range完全相同,所不同的是生成的不是一个数组,而是一个生成器;
例如:
>>> xrange(5)
xrange(5)
>>> list(xrange(5))
[0, 1, 2, 3, 4]
>>> xrange(1,5)
xrange(1, 5)
>>> list(xrange(1,5))
[1, 2, 3, 4]
>>> xrange(0,6,2)
xrange(0, 6, 2)
>>> list(xrange(0,6,2))
[0, 2, 4]
81、zip函数说明
def zip(seq1, seq2, *more_seqs): # known special case of zip """ zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence. """ pass
实现从多个序列生一个元组列表迭代子返回,即是从每个序列里获取一项,然后把所有的项生成元组,再把这些元组生成列表返回。如果有多个序列,以最短的序列为元组的个数。如果在参数前面添加*表示反向处理,即是从元组列表转换为分离的列表返回;
例如:
>>> l = [1, 2, 3]
>>> x = [4, 5, 6]
>>> print(list(zip(l, x)))
[(1, 4), (2, 5), (3, 6)]
>>> x = [4, 5]
>>> print(list(zip(l, x)))
[(1, 4), (2, 5)]
>>> y = (7, 8, 9)
>>> print(list(zip(l, x, y)))
[(1, 4, 7), (2, 5, 8)]
>>> lxy = list(zip(l, x, y))
>>> print(list(zip(*lxy)))
[(1, 2), (4, 5), (7, 8)]
82、__import__函数说明
def __import__(name, globals={}, locals={}, fromlist=[], level=-1): # real signature unknown; restored from __doc__ """ __import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module Import a module. Because this function is meant for use by the Python interpreter and not for general use it is better to use importlib.import_module() to programmatically import a module. The globals argument is only used to determine the context; they are not modified. The locals argument is unused. The fromlist should be a list of names to emulate ``from name import ...'', or an empty list to emulate ``import name''. When importing a module from a package, note that __import__('A.B', ...) returns package A when fromlist is empty, but its submodule B when fromlist is not empty. Level is used to determine whether to perform absolute or relative imports. -1 is the original strategy of attempting both absolute and relative imports, 0 is absolute, a positive number is the number of parent directories to search relative to the current module. """ pass
实现导入模块的功能,主要为了语句import的功能而实现的,大多数情况之下,是不需要直接使用这个函数,比如想动态地加载模块,才需要使用这个函数;
例如:
import glob,os modules = [] for module_file in glob.glob("*-plugin.py"): try: module_name,ext = os.path.splitext(os.path.basename(module_file)) module = __import__(module_name) modules.append(module) except ImportError: pass #ignore broken modules #say hello to all modules for module in modules: module.hello()