首页 > 应用开发 > Python > Python内置函数示例
at 0x02E9B840, file "", line 1> >>> exec(test) hello >>> ``` ## complex() 创建一个复数 ```python >>> complex(13,18) (13+18j) >>> ``` ## delattr() 删除对象属性 ``` #!/usr/bin/python # -*- coding: UTF-8 -*- class Coordinate: x = 10 y = -5 z = 0 point1 = Coordinate() print('x = ',point1.x) print('y = ',point1.y) print('z = ',point1.z) delattr(Coordinate, 'z') print('--删除 z 属性后--') print('x = ',point1.x) print('y = ',point1.y) # 触发错误 print('z = ',point1.z) ``` 输出结果: ```python >>> x = 10 y = -5 z = 0 --删除 z 属性后-- x = 10 y = -5 Traceback (most recent call last): File "C:\Users\fdgh\Desktop\test.py", line 22, in print('z = ',point1.z) AttributeError: 'Coordinate' object has no attribute 'z' >>> ``` ## dict() 创建数据字典 ```python >>> dict() {} >>> dict(a=1,b=2) {'a': 1, 'b': 2} >>> ``` ## dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表 ```python >>> dir() ['Coordinate', '__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'point1', 'y'] >>> ``` ## divmod() 分别取商和余数 ```python >>> divmod(11,2) (5, 1) >>> ``` ## enumerate() 返回一个可以枚举的对象,该对象的next()方法将返回一个元组 ```python >>> blxt = ['a','b','c','d'] >>> list(enumerate(blxt)) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] >>> ``` ## eval() 将字符串str当成有效表达式来求值并返回计算结果取出字符串中内容 ```python >>> blxt = "5+1+2" >>> eval(blxt) 8 >>> ``` ## exec() 执行字符串或complie方法编译过的字符串,没有返回值 ```python >>> blxt = "print('hello')" >>> test = compile(blxt,'','exec') >>> test at 0x02E9B840, file "", line 1> >>> exec(test) hello >>> ``` ## filter() 过滤器,构建一个序列 ```python #过滤列表中所有奇数 #!/usr/bin/python # -*- coding: UTF-8 -*- def is_odd(n): return n % 2 == 1 newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(newlist) ``` 输出结果: ```python [ 1, 3, 5, 7, 9 ] ``` ## float() 将一个字符串或整数转换为浮点数 ```python >>> float(3) 3.0 >>> float(10) 10.0 >>> ``` ## format() 格式化输出字符串 ```python >>> "{0} {1} {3} {2}".format("a","b","c","d") 'a b d c' >>> print("网站名:{name},地址:{url}".format(name="blxt",url="www.blxt.best")) 网站名:blxt,地址:www.blxt.best >>> ``` ## frozenset() 创建一个不可修改的集合 ```python >>> frozenset([2,4,6,6,7,7,8,9,0]) frozenset({0, 2, 4, 6, 7, 8, 9}) >>> ``` ## getattr() 获取对象属性 ```python >>>class A(object): ... bar = 1 ... >>> a = A() >>> getattr(a, 'bar') # 获取属性 bar 值 1 >>> getattr(a, 'bar2') # 属性 bar2 不存在,触发异常 Traceback (most recent call last): File "", line 1, in AttributeError: 'A' object has no attribute 'bar2' >>> getattr(a, 'bar2', 3) # 属性 bar2 不存在,但设置了默认值 3 >>> ``` ## globals() 返回一个描述当前全局变量的字典 ```python >>> print(globals()) # globals 函数返回一个全局变量的字典,包括所有导入的变量。 {'__builtins__': , '__name__': '__main__', '__doc__': None, 'a': 'runoob', '__package__': None} ``` ## hasattr() 函数用于判断对象是否包含对应的属性 ```python >>>class A(object): ... bar = 1 ... >>> a = A() >>> hasattr(a,'bar') True >>> hasattr(a,'test') False ``` ## hash() 返回对象的哈希值 ```python >>>class A(object): ... bar = 1 ... >>> a = A() >>> hash(a) -2143982521 >>> ``` ## help() 返回对象的帮助文档 ```python >>>class A(object): ... bar = 1 ... >>> a = A() >>> help(a) Help on A in module __main__ object: class A(builtins.object) | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | bar = 1 >>> ``` ## id() 返回对象的内存地址 ```python >>>class A(object): ... bar = 1 ... >>> a = A() >>> id(a) 56018040 >>> ``` ## input() 获取用户输入内容 ```python >>> input() ... test 'test' >>> ``` ## int() 用于将一个字符串或数字转换为整型 ```python >>> int('14',16) 20 >>> int('14',8) 12 >>> int('14',10) 14 >>> ``` ## isinstance() 来判断一个对象是否是一个已知的类型,类似 type() ```python >>> test = 100 >>> isinstance(test,int) True >>> isinstance(test,str) False >>> ``` ## issubclass() 用于判断参数 class 是否是类型参数 classinfo 的子类 ```php #!/usr/bin/python # -*- coding: UTF-8 -*- class A: pass class B(A): pass print(issubclass(B,A)) # 返回 True ``` ## iter() 返回一个可迭代对象,sentinel可省略 ```python >>>lst = [1, 2, 3] >>> for i in iter(lst): ... print(i) ... 1 2 3 ``` ## len() 返回对象的长度 ```python >>> dic = {'a':100,'b':200} >>> len(dic) 2 >>> ``` ## list() 返回可变序列类型 ```python >>> a = (123,'xyz','zara','abc') >>> list(a) [123, 'xyz', 'zara', 'abc'] >>> ``` ## map() 返回一个将function应用于iterable中每一项并输出其结果的迭代器 ```python >>>def square(x) : # 计算平方数 ... return x ** 2 ... >>> map(square, [1,2,3,4,5]) # 计算列表各个元素的平方 [1, 4, 9, 16, 25] >>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函数 [1, 4, 9, 16, 25] # 提供了两个列表,对相同位置的列表数据进行相加 >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) [3, 7, 11, 15, 19] ``` ## max() 返回最大值 ```python >>> max (1,2,3,4,5,6,7,8,9) 9 >>> ``` ## min() 返回最小值 ```python >>> min (1,2,3,4,5,6,7,8) 1 >>> ``` ## memoryview() 返回给定参数的内存查看对象(memory view) ```python >>>v = memoryview(bytearray("abcefg", 'utf-8')) >>> print(v[1]) 98 >>> print(v[-1]) 103 >>> print(v[1:4]) >>> print(v[1:4].tobytes()) b'bce' >>> ``` ## next() 返回可迭代对象的下一个元素 ```python >>> a = iter([1,2,3,4,5]) >>> next(a) 1 >>> next(a) 2 >>> next(a) 3 >>> next(a) 4 >>> next(a) 5 >>> next(a) Traceback (most recent call last): File "", line 1, in next(a) StopIteration >>> ``` ## object() 返回一个没有特征的新对象 ```python >>> a = object() >>> type(a) >>> ``` ## open() 返回文件对象 ```python >>>f = open('test.txt') >>> f.read() '123/123/123' ``` ## pow() base为底的exp次幂,如果mod给出,取余 ```python >>> pow (3,1,4) 3 >>> ``` ## print() 打印对象 ## class property() 返回property属性 ```python class C(object): 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.") ``` ## range() 生成一个不可变序列 ```python >>> range(10) range(0, 10) >>> ``` ## reversed() 返回一个反向的iterator ```python >>> a = 'test' >>> a 'test' >>> print(list(reversed(a))) ['t', 's', 'e', 't'] >>> ``` ## round() 四舍五入 ```python >>> round (3.33333333,1) 3.3 >>> ``` ## class set() 返回一个set对象,可实现去重 ```python >>> a = [1,2,3,4,5,5,6,5,4,3,2] >>> set(a) {1, 2, 3, 4, 5, 6} >>> ``` ## class slice() 返回一个表示有1range所指定的索引集的slice对象 ```python >>> a = [1,2,3,4,5,5,6,5,4,3,2] >>> a[slice(0,3,1)] [1, 2, 3] >>> ``` ## sorted() 对所有可迭代的对象进行排序操作 ```python >>> a = [1,2,3,4,5,5,6,5,4,3,2] >>> sorted(a,reverse=True) [6, 5, 5, 5, 4, 4, 3, 3, 2, 2, 1] >>> ``` ## @staticmethod 将方法转换为静态方法 ```python #!/usr/bin/python # -*- coding: UTF-8 -*- class C(object): @staticmethod def f(): print('blxt'); C.f(); # 静态方法无需实例化 cobj = C() cobj.f() # 也可以实例化后调用 ``` 输出结果: ```python test test ``` ## sum() 求和 ```python a = [1,2,3,4,5,5,6,5,4,3,2] >>> sum(a) 40 >>> ``` ## super() 返回一个代理对象 ```python class A: def add(self, x): y = x+1 print(y) class B(A): def add(self, x): super().add(x) b = B() b.add(2) # 3 ``` ## tuple() 不可变的序列类型 ```python >>> a = 'www' >>> b =tuple(a) >>> b ('w', 'w', 'w') >>> ``` ## zip() 将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表 ```python >>>a = [1,2,3] >>> b = [4,5,6] >>> c = [4,5,6,7,8] >>> zipped = zip(a,b) # 打包为元组的列表 [(1, 4), (2, 5), (3, 6)] >>> zip(a,c) # 元素个数与最短的列表一致 [(1, 4), (2, 5), (3, 6)] >>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式 [(1, 2, 3), (4, 5, 6)] ``` ## [点击这里跳转个人博客](https://www.blxt.best)
at 0x02E9B840, file "", line 1> >>> exec(test) hello >>> ``` ## filter() 过滤器,构建一个序列 ```python #过滤列表中所有奇数 #!/usr/bin/python # -*- coding: UTF-8 -*- def is_odd(n): return n % 2 == 1 newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(newlist) ``` 输出结果: ```python [ 1, 3, 5, 7, 9 ] ``` ## float() 将一个字符串或整数转换为浮点数 ```python >>> float(3) 3.0 >>> float(10) 10.0 >>> ``` ## format() 格式化输出字符串 ```python >>> "{0} {1} {3} {2}".format("a","b","c","d") 'a b d c' >>> print("网站名:{name},地址:{url}".format(name="blxt",url="www.blxt.best")) 网站名:blxt,地址:www.blxt.best >>> ``` ## frozenset() 创建一个不可修改的集合 ```python >>> frozenset([2,4,6,6,7,7,8,9,0]) frozenset({0, 2, 4, 6, 7, 8, 9}) >>> ``` ## getattr() 获取对象属性 ```python >>>class A(object): ... bar = 1 ... >>> a = A() >>> getattr(a, 'bar') # 获取属性 bar 值 1 >>> getattr(a, 'bar2') # 属性 bar2 不存在,触发异常 Traceback (most recent call last): File "", line 1, in AttributeError: 'A' object has no attribute 'bar2' >>> getattr(a, 'bar2', 3) # 属性 bar2 不存在,但设置了默认值 3 >>> ``` ## globals() 返回一个描述当前全局变量的字典 ```python >>> print(globals()) # globals 函数返回一个全局变量的字典,包括所有导入的变量。 {'__builtins__': , '__name__': '__main__', '__doc__': None, 'a': 'runoob', '__package__': None} ``` ## hasattr() 函数用于判断对象是否包含对应的属性 ```python >>>class A(object): ... bar = 1 ... >>> a = A() >>> hasattr(a,'bar') True >>> hasattr(a,'test') False ``` ## hash() 返回对象的哈希值 ```python >>>class A(object): ... bar = 1 ... >>> a = A() >>> hash(a) -2143982521 >>> ``` ## help() 返回对象的帮助文档 ```python >>>class A(object): ... bar = 1 ... >>> a = A() >>> help(a) Help on A in module __main__ object: class A(builtins.object) | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | bar = 1 >>> ``` ## id() 返回对象的内存地址 ```python >>>class A(object): ... bar = 1 ... >>> a = A() >>> id(a) 56018040 >>> ``` ## input() 获取用户输入内容 ```python >>> input() ... test 'test' >>> ``` ## int() 用于将一个字符串或数字转换为整型 ```python >>> int('14',16) 20 >>> int('14',8) 12 >>> int('14',10) 14 >>> ``` ## isinstance() 来判断一个对象是否是一个已知的类型,类似 type() ```python >>> test = 100 >>> isinstance(test,int) True >>> isinstance(test,str) False >>> ``` ## issubclass() 用于判断参数 class 是否是类型参数 classinfo 的子类 ```php #!/usr/bin/python # -*- coding: UTF-8 -*- class A: pass class B(A): pass print(issubclass(B,A)) # 返回 True ``` ## iter() 返回一个可迭代对象,sentinel可省略 ```python >>>lst = [1, 2, 3] >>> for i in iter(lst): ... print(i) ... 1 2 3 ``` ## len() 返回对象的长度 ```python >>> dic = {'a':100,'b':200} >>> len(dic) 2 >>> ``` ## list() 返回可变序列类型 ```python >>> a = (123,'xyz','zara','abc') >>> list(a) [123, 'xyz', 'zara', 'abc'] >>> ``` ## map() 返回一个将function应用于iterable中每一项并输出其结果的迭代器 ```python >>>def square(x) : # 计算平方数 ... return x ** 2 ... >>> map(square, [1,2,3,4,5]) # 计算列表各个元素的平方 [1, 4, 9, 16, 25] >>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函数 [1, 4, 9, 16, 25] # 提供了两个列表,对相同位置的列表数据进行相加 >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) [3, 7, 11, 15, 19] ``` ## max() 返回最大值 ```python >>> max (1,2,3,4,5,6,7,8,9) 9 >>> ``` ## min() 返回最小值 ```python >>> min (1,2,3,4,5,6,7,8) 1 >>> ``` ## memoryview() 返回给定参数的内存查看对象(memory view) ```python >>>v = memoryview(bytearray("abcefg", 'utf-8')) >>> print(v[1]) 98 >>> print(v[-1]) 103 >>> print(v[1:4]) >>> print(v[1:4].tobytes()) b'bce' >>> ``` ## next() 返回可迭代对象的下一个元素 ```python >>> a = iter([1,2,3,4,5]) >>> next(a) 1 >>> next(a) 2 >>> next(a) 3 >>> next(a) 4 >>> next(a) 5 >>> next(a) Traceback (most recent call last): File "", line 1, in next(a) StopIteration >>> ``` ## object() 返回一个没有特征的新对象 ```python >>> a = object() >>> type(a) >>> ``` ## open() 返回文件对象 ```python >>>f = open('test.txt') >>> f.read() '123/123/123' ``` ## pow() base为底的exp次幂,如果mod给出,取余 ```python >>> pow (3,1,4) 3 >>> ``` ## print() 打印对象 ## class property() 返回property属性 ```python class C(object): 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.") ``` ## range() 生成一个不可变序列 ```python >>> range(10) range(0, 10) >>> ``` ## reversed() 返回一个反向的iterator ```python >>> a = 'test' >>> a 'test' >>> print(list(reversed(a))) ['t', 's', 'e', 't'] >>> ``` ## round() 四舍五入 ```python >>> round (3.33333333,1) 3.3 >>> ``` ## class set() 返回一个set对象,可实现去重 ```python >>> a = [1,2,3,4,5,5,6,5,4,3,2] >>> set(a) {1, 2, 3, 4, 5, 6} >>> ``` ## class slice() 返回一个表示有1range所指定的索引集的slice对象 ```python >>> a = [1,2,3,4,5,5,6,5,4,3,2] >>> a[slice(0,3,1)] [1, 2, 3] >>> ``` ## sorted() 对所有可迭代的对象进行排序操作 ```python >>> a = [1,2,3,4,5,5,6,5,4,3,2] >>> sorted(a,reverse=True) [6, 5, 5, 5, 4, 4, 3, 3, 2, 2, 1] >>> ``` ## @staticmethod 将方法转换为静态方法 ```python #!/usr/bin/python # -*- coding: UTF-8 -*- class C(object): @staticmethod def f(): print('blxt'); C.f(); # 静态方法无需实例化 cobj = C() cobj.f() # 也可以实例化后调用 ``` 输出结果: ```python test test ``` ## sum() 求和 ```python a = [1,2,3,4,5,5,6,5,4,3,2] >>> sum(a) 40 >>> ``` ## super() 返回一个代理对象 ```python class A: def add(self, x): y = x+1 print(y) class B(A): def add(self, x): super().add(x) b = B() b.add(2) # 3 ``` ## tuple() 不可变的序列类型 ```python >>> a = 'www' >>> b =tuple(a) >>> b ('w', 'w', 'w') >>> ``` ## zip() 将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表 ```python >>>a = [1,2,3] >>> b = [4,5,6] >>> c = [4,5,6,7,8] >>> zipped = zip(a,b) # 打包为元组的列表 [(1, 4), (2, 5), (3, 6)] >>> zip(a,c) # 元素个数与最短的列表一致 [(1, 4), (2, 5), (3, 6)] >>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式 [(1, 2, 3), (4, 5, 6)] ``` ## [点击这里跳转个人博客](https://www.blxt.best)
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69956585/viewspace-2692885/ ,如需转载,请注明出处,否则将追究法律责任。
注册时间:2019-12-05