Python 内置函数
Return the absolute value of a number. The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned.
返回一个数的绝对值。参数可以是整形或资格浮点数。如果参数是复数,则该复数的模(|z|=√a²+b²,)被返回。
For example:
print abs(1) # 1
print abs(-1) # 1
print abs(1.0) # 1.0
print abs(-10) # 1.0
print abs(3+4j) # 5
Return True if all elements of the iterable are true (or if the iterableis empty). Equivalent to:
如果可迭代对象的所有元素都为True或者该对象为空则返回真, 否则返回False。相当于:
def all(iterable):
for element in iterable:
if not element:
return False
return True
Return True if any element of the iterable are true, if the iterable is empty(all elements of the iterable are false), return False. Equivalent to:
如果可迭代对象的任一元素为true则返回True, 如果可迭代对象的所有元素为false或者该对象为空则返回False。相当于:
def any(iterable):
for element in iterable:
if element:
return True
return False
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.
类似于repr(),返回一个对象的可打印的字符串表示,在字符串中的转义非ASCI字符通过repr()函数使用\x, \u, \U转义字符返回,产生的字符串和Python2中的repr()函数
类似。(换句话说就是将对象转化为一个ASCII字符表示的字符串。)
ascii("哇哈哈abc") # "'\\u54c7\\u54c8\\u54c8abc'"
repr("哇哈哈abc") # "'哇哈哈abc'"
class Test:
__init__(self, num):
self.num = num
__index__(self):
return self.num
bin(10) # '0b1010'
bin(A(10)) # '0b1010'
将一个值使用标准的真值测试过程转化为Boolean类型. 如果x为false或者x为缺省值, 返回False,否则返回True.另外bool是一个int类型的子类.bool不能被进一步的继承.
它只有两个实例True和False(详见Boolean值).
bool(1) # True
bool(0) # False
bool(-1) # True
bool() # False
described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.
The optional source parameter can be used to initialize the array in a few different ways:
If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
If it is an integer, the array will have that size and will be initialized with null bytes.
If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.
Without an argument, an array of size 0 is created.
返回一个新的字节数组. Bytearrayle类型是一个数值大小介于 0<= x< 256 之间的可变序列. 它拥有大多数可变序列类型所拥有的方法,这些方法在可变序列类型
(Mutable Sequence Types)中被描述, 同时拥有数组的(bytes)的大多数方法.
选项source参数可以被用来以不同的方式初始化字符数组:
如果是字符串, 必须指出encoding选项(errors选项是可选的), bytearray将使用str.encode()方法将字符串转化为数组.
如果是整型, 该数字将作为被创建字节数组的大小, 并且该字节数组元素都被null初始化.
如果一个对象遵守buffer接口, 该对象的只读buffer将被用来初始化数组.如果是可迭代对象, 迭代的返回值必须是一个介于0<= x< 256 之间的整型,
这些整型值被用来初始化 数组.
如果没有参数, 容量为0的数组被创建.
class Iter:
def __init__(self, num):
self.num = num
def __iter__(self):
return self
def __next__(self):
if self.num == 0:
raise StopIteration
else:
self.num = self.num - 1
return self.num
def bytearray_test():
b1 = bytearray() # b''
b2 = bytearray("abc", "gbk") # b'abc'
b3 = bytearray(10) # b'\00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b4 = bytearray(Iter(10)) # b'\t\x08\x07\x06\x05\x04\x03\x02\x01\x00'
non-mutating methods and the same indexing and slicing behavior.
Accordingly, constructor arguments are interpreted as for bytearray().
Bytes objects can also be created with literals, see String and Bytes literals.
返回一个新的数组对象, 数组是一个整型介于0<= x < 256之间的不可变序列. byte是bytearray的一个不可变版本- 它有相似的不可变方法, 索引和切片行为.
另外, 构造函数的参数以bytearray的解释方式被解释.
数组对象可以使用字面值创建, 具体的用法请看 String and Bytes literals.
Return True if theobject argument appears callable,False if not. If this returns true, it is still possible that a call fails, but if it is false, callingobject will never succeed.
Note that classes are callable (calling a class returns a new instance);instances are callable if their class has a__call__() method.
New in version 3.2:This function was first removed in Python 3.0 and then brought back in Python 3.2.
如果该参数是可以被调用的那么返回True, 否则返回False. 如果返回True 这个参数表示的对象仍然可能调用失败, 但是如果返回False, 这个对象一定不会调用成功.
注意: 类是可以被调用的(调用一个类将返回该类的一个实例); 如果类的实例有一个__call__()方法 那么该实例是可以被调用,
该函数在3.0版本中被移除了, 但是在3.2中该方法又回来了.
#!/usr/bin/env python
#-*- encoding: utf-8 -*-
class TestCall:
def __call__(self):
print("the instance has been invoked!")
pass
class NotTestCall:
pass
def func():
pass
if __name__ == '__main__':
print(callable(func)) # True
print(callable(TestCall)) # True
print(callable(TestCall())) # True
print(callable(NotTestCall)) # True
print(callable(NotTestCall())) # False
pass
Return the string representing a character whose Unicode codepoint is the integer i. For example,chr(97) returns the string'a'. This is the inverse of ord().
The valid range for the argument is from 0 through1,114,111 (0x10FFFF in base 16).ValueError will be raised if i is outside that range.
返回一个Unicode码点是整数i所表示的字符的字符串. chr()的反解析函数是ord(). 参数的取值范围为0~0x10FFFF. 如果这个参数超过该范围则会抛出ValueError.
chr(97) # 'a'
Return a class method for function.
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, ...):
pass
或者
class C:
def f(cls, arg1, arg2, ...):
pass
f = classmethod(f)
class (such as C.f()) or on an instance (suchasC().f()). The instance is ignored except for its class. If a classmethod 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,seestaticmethod() in
this section.
@classmethod是一个函数修饰符--详见 Function definitions for details中的函数描述符定义.被@classmethod修饰的方法及可以被类调用(C.f())也可以被类的实例调用(C().f()). 通过类实例调用的时候,该实例被忽略. 如果一个类方法被子类调用, 那么这个子类
将作为该方法的隐式的第一个参数. Python的类方法不同于C++/Java的静态方法. 如果你想了解静态方法,请看staticmethod()这章.
#!/usr/bin/env python
#-*- encoding: utf-8 -*-
class ClassmethodTest():
def test01(self):
pass
@classmethod
def test02(self):
pass
pass
if __name__ == '__main__':
print(ClassmethodTest.test01(ClassmethodTest())) # Only a normal function
print(ClassmethodTest().test01) # Instance method
print(ClassmethodTest.test02()) # Class method.
pass
Return a static method for function.
A static method does not receive an implicit first argument. To declare a staticmethod, use this idiom:
返回一个函数的静态方法(就是将一个函数转化为静态方法).
静态方法不会接受一个隐式参数作为第一个参数,为了声明一个静态方法,使用这样的用法:
class C:
@staticmethod
def f(arg1, arg2, ...):
pass
或者
class C:
def f(arg1, arg2, ...):
pass
f = staticmethod(f)
The @staticmethod form is a functiondecorator – see thedescription of function definitions inFunction definitions for details.
It can be called either on the class (such as C.f()) or on an instance (suchas C().f()). The instance is ignored except for its class.
Static methods in Python are similar to those found in Java or C++. Also see classmethod() for a variant that is useful for creating alternate class constructors.
@staticmethod是一个函数修饰符--详见Function definitions for details中的函数描述符定义.
被@staticmethod修饰的方法及可以被类调用(C.f())也可以被类的实例调用(C().f()). 通过类实例调用的时候,该实例被忽略.
Python的静态方法类似与C++/Java的静态方法. 另请参看classmethod(), 它是代替类构造函数的一个很有用的变种。
如果你想了解静态方法,请看staticmethod()这章.
#!/usr/bin/env python
#-*- encoding: utf-8 -*-
class StaticmethodTest():
def test01(self):
pass
@staticmethod
def test02():
pass
pass
if __name__ == '__main__':
print(StaticmethodTest.test01(StaticmethodTest())) # Only a normal function
print(StaticmethodTest().test01) # Instance method
print(StaticmethodTest.test02()) # Static method.
pass
Create a complex number with the value real +imag*j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a
complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric
type (including complex). If imag is omitted, it defaults to zero and the function serves as a numeric conversion function likeint()andfloat(). If both arguments
are omitted, returns0j.
Note: When converting from a string, the string must not contain whitespace around the central+ or- operator. For example,complex('1+2j') is fine, but
complex('1+2j') raisesValueError.
用(real+img*j)的形式创建一个复数或者将一个字符串或者数字转化为一个复数。如果第一个参数为字符串, 该字符串将被解析为一个复数,并且在该函数调用时
必须没有第二个参数. 该函数的第二个参数永远不会为字符串. 该函数的任何参数都可以是数值类型(包括复数). 如果img被省略了, 该值默认为0, 并且该函数会
将其它类型的值转换成数值类型, 作用类似于int()和float().如果两个参数都被省略了, 该函数返回0j.
注意: 当将一个字符串转换成复数时, 该字符串的+/-号两边不能包含空格. 例如, 复数complex('1+2j')是正穷的, 但是complex('1 + 2j')会抛出一个ValueError异常.
#!/usr/bin/env python
#-*- encoding: utf-8 -*-
if __name__ == '__main__':
complex() # 0j
complex(1) # 1+0j
complex(1, 2) # 1+2j
complex('1') # 1+0j, Like int() and float()
complex('1+2j') # 1+2j, Fine
omplex('1 + 2j') # ValueError, Malformed
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute.
For example, getattr(x, ’foobar’) is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
返回对象指定属性值. 属性名必须是一个字符串. 如果字符串是对象的属性名之一, 结果则是该属性的值.
例如, getattr(x, ’foobar’)等价于x.foobar. 如果属性名不存则返回默认值,否则抛出AttributeError异常.
class A:
pass
if __name__ == '__main__':
A.a = 10
getattr(A,'a') # 10
getattr(A.'b', 20) # 20
getattr(A,'c') # AttributeError
This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute.
The function assigns the value to the attribute, provided the object allows it.
For example, setattr(x, ’foobar’, 123) is equivalent to x.foobar = 123.
该函数是getattr的配对函数. 函数参数是一个对象, 一个字符串和一个任意值. 第二个参数所表示的字符串可以是一个已经存在的属性或者新的属性.
如果提供的对象允许这么做的话, 这个函数给特定的属性指定一个值,
例如, setattr(x, 'foobar', 123)等价于x.foobar = 123.
class A:
pass
if __name__ == '__main__':
A.a = 10
setattr(A,'a',100) # Setting an always existing attribute
setattr(A.'b', 20) # Setting a new attribute
This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes.
The function deletes the named attribute, provided the object allows it. For example, delattr(x, ’foobar’) is equivalent to del x.foobar.
这个函数是相对于setattr()的. 该函数的参数是一个对象和一个字符串. 第二个参数所表示的字符串必须是一个已经存在的属性.
这个函数删除对象的具名属性, 如果对象允许这么做的话. 例如, delattr(x,'foobar')等价于del x.foobar.
class A:
pass
if __name__ == '__main__':
a = A()
a.a = 10
a.b = 20
del a.a
delattr(a,'b')
pass
Create a new dictionary. The dict object is the dictionary class. See dict and Mapping Types — dict for documentation about this class.
创建一个新的字典. 这个字典对象是一个字典类.请参阅字典和映射类型相关的文档.
if __name__ == '__main__':
dict() # dict()
dict({'one':1, 'two':2 }) # dict(mapping,**kwarg)
dict(enumerate((1,2))) # dict(iterable,**kwarg)
dict(one=1, two=2) # dict(**kwarg)
pass
其中, 如果(4)省略参数和(1)是一个效果, 写(4)是为了突出封包.
Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom
__getattr__() or__getattribute__() function to customize the waydir() reports their attributes.
If the object does not provide __dir__(), the function tries its best to gather information from the object’s__dict__ attribute, if defined, and from its type object.
The resulting list is not necessarily complete, and may be inaccurate when the object has a custom__getattr__().
The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:
If the object is a module object, the list contains the names of the module’s attributes.
If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.
The resulting list is sorted alphabetically. For example:
如果没有参数, 返回当前域的所有名称的列表. 当有参数的时候, 尝试返回该对象的所有有效属性列表.
如果对象有一个__dict__()方法, 这个方法将被调用并且该方法必须返回对象的参数列表. 这就允许对象实现一个自定义的__getattr__()方法或者__getattribute__()方法
来自定义dir()函数上报对象属性的方式.