4000-520-616
欢迎来到免疫在线!(蚂蚁淘生物旗下平台)  请登录 |  免费注册 |  询价篮
主营:原厂直采,平行进口,授权代理(蚂蚁淘为您服务)
咨询热线电话
4000-520-616
当前位置: 首页 > 新闻动态 >
新闻详情
Python 官方文档解读(1):66 个内置函数
来自 : 个人图书馆 发布时间:2021-03-25

closefd :如果 file 是一个字符串,那么 closefd 只能是 False,否则将引发错误;如果 file 是一个文件描述符,那么 closefd 可以被设置为 True,此时这个文件描述符对应的文件即使被关闭了也仍然保持打开。

opener :一个 callable,要被打开的文件会使用 opener(file, flags) 来打开,opener()需要返回一个打开的文件描述符(比如os.open())。实例:

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

输入一个字符,返回这个字符的 Unicode 码点。例如ord(\'a\')返回97。

47. pow(x, y[, z])

返回 x 的 y 次幂(模 z)。

48. print(**objects, sep=\' \', end=\'\\n\', file=sys.stdout, flush=False*)

所有的非关键词参数都通过str()被转换成字符串,以 sep 分隔,以 end 结尾,并将字符串输出到 file。flush 设为True能够强制冲洗缓冲区。

49. class property(fget=None, fset=None, fdel=None, doc=None)

参考我的这篇文章。

50. range(stop), range(start, stop[, step])

返回一个 range 对象。参考 Sequence Types — list, tuple, range。

51.repr(object)

返回一个代表 object 的字符串。对于许多类型,比如内置类型,repr()返回的字符串放到eval()里能直接返回那个对象;对于其他类型,它一般返回一个字符串,两边是尖括号,里面包括对象的类型和额外信息(比如名字和内存地址)。一个类可以通过重写__repr__()方法来控制repr()的输出。

52. reversed(seq)

返回一个逆序的迭代器。seq 必须是一个拥有__reversed__()方法的对象,或者它支持序列协议(拥有__len__()方法和从 0 作为参数开始的__getitem__()方法)。

53. round(number[, ndigits])

返回 number 在小数点后舍入到 ndigits 精度的结果。如果省略 ndigits,则返回一个舍入后的整数。

注意:舍入方法不是四舍五入,而是靠近最近的偶数。举例:

 round(0.5) round(-0.5) round(1.5)2

对于一个普通的对象,round()会尝试调用对象的__round__()方法。

round()对浮点数的行为有时会让人琢磨不透:round(2.675, 2)按理说应该返回2.68,但实际上它返回2.67。原因还是 Python 的浮点精度问题。

54. class set([iterable])

返回一个 set 对象。参看 Set Types — set, frozenset。

55. setattr(object, name, value)

和 getattr() 搭配使用。setattr(x, \'foobar\', 123) 相当于
x.foobar = 123。

56. class slice(stop), slice(start, stop[, step])

返回一个 slice 对象,用于对序列切片,代表一个在 range(start, stop, step)的下标。Python 的扩展下标语法 (在 Python 2.3 引入)也可以生成一个 slice 对象。示例:

 class C(object):... def __getitem__(self, val):... print val c = C() c[1:2,3:4](slice(1, 2, None), slice(3, 4, None)) c[5:6,7](slice(5, 6, None), 7)
57. sorted(iterable, *, key=None, reverse=False)

返回一个排序后的 iterable (升序)。key 是一个 callable,可以用来对复杂对象指定“按什么排序”。

这个函数保证是稳定的,即对于“相等”的两个元素,它们的相对位置不会改变。

58. @staticmethod

将一个方法转换为静态方法。

静态方法不接收第一个 implicit 参数(比如 self和cls)。使用方法为:

class C: # 使用装饰器 @staticmethod def f(arg1, arg2, ...): ... # 不使用装饰器 builtin_open = staticmethod(open)

注意它的 classmethod 的区别:classmethod 可以用来访问和更改这个类的内部状态和属性,但 staticmethod 不能;staticmethod 的主要作用是把一些和某个类相关的工具函数放到这个类的命名空间下。参看 class method vs static method in Python。

59. class str(object=\'\'), str(object=b\'\', encoding=\'utf-8\', errors=\'strict\')

返回一个字符串对象。

60. sum(iterable[, start])

将 iterable 的元素求和,再加上 start ,得到总和并返回。start 默认为 0。通常用于整数类型求和。

对于其他类型有更好的求和方法,比如串联字符串使用\'\'.join(sequence)最快;用扩展精度求和浮点数,使用math.fsum();将 iterable 串联起来可以使用itertools.chain()。

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

返回一个代理对象,它能把对方法的调用传递给 type 的父类或兄弟类。

一个类的__mro__动态地记录了“方法解析搜索顺序” (Method Resuolution search Order),像是一个继承链,getattr()和super()使用__mro__来解析对方法的访问。例如:

 class myList(list):... x = 1 myList.__mro__( class \'__main__.myList\' , class \'list\' , class \'object\' )

super()主要有两个用途:

避免显式地使用基类用于多重继承

单继承例子:

class Mammal(object): def __init__(self, mammalName): print(mammalName, \'is a warm-blooded animal.\')class Dog(Mammal): def __init__(self): print(\'Dog has four legs.\') super().__init__(\'Dog\')d1 = Dog()

由于避免直接使用Mammal.__init__(self, \'Dog\'),有一天改变了Dog的基类后代码仍然是可用的。

多重继承例子:

class Animal: def __init__(self, animalName): print(animalName, \'is an animal.\');class Mammal(Animal): def __init__(self, mammalName): print(mammalName, \'is a warm-blooded animal.\') super().__init__(mammalName)class NonWingedMammal(Mammal): def __init__(self, NonWingedMammalName): print(NonWingedMammalName, \"can\'t fly.\") super().__init__(NonWingedMammalName)class NonMarineMammal(Mammal): def __init__(self, NonMarineMammalName): print(NonMarineMammalName, \"can\'t swim.\") super().__init__(NonMarineMammalName)class Dog(NonMarineMammal, NonWingedMammal): def __init__(self): print(\'Dog has 4 legs.\'); super().__init__(\'Dog\')d = Dog()print(\'\')bat = NonMarineMammal(\'Bat\') 

输出为:

Dog has 4 legs.Dog can\'t swim.Dog can\'t fly.Dog is a warm-blooded animal.Dog is an animal.Bat can\'t swim.Bat is a warm-blooded animal.Bat is an animal.

注意到:一行super().__init__(\'Dog\')实际上把它两个基类的__init__()都依次调用了,先调用的是第一个基类,再调用第二个基类。

关于super()在 Python 多重继承中的问题,参看 How does Python\'s super() work with multiple inheritance?

关于 MRO,可以参看 Guido van Rossum 的这一篇文章:Method Resolution Order。

参看 guide to using super()。

62. tuple([iterable])

返回一个 tuple 对象。

63. class type(object), type(name, bases, dict)

返回 object 的类型(object.__class__)。

通过三个参数,可以动态构建 class。例如下面两种写法等价:

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

所有“类”的 type 都是 type,包括 type。

64. vars([object])

返回一个对象的__dict__属性。这个对象可以是模块、类、实例等任何对象。

没有参数时,vars()和locals()等价。

65. zip(**iterables*)

将不同 iterables 里的元素融合,返回一个新的 tuple 的迭代器,第 i\" role=\"presentation\">ii 个 tuple 是所有传入 iterable 里的第 i\" role=\"presentation\">ii 个元素。示例:

 x = [1, 2, 3] y = [4, 5, 6] zipped = zip(x, y) list(zipped)[(1, 4), (2, 5), (3, 6)]

zip()搭配*使用可以用来解压:

 x2, y2 = zip(*zip(x, y)) x == list(x2) and y == list(y2)True
66. __import__(name, globals=None, locals=None, fromlist=(), level=0)

这个函数被import语句调用。你可以通过重写这个函数来改变import语句的行为,只要引入builtins模块并对builtins.__import__赋值即可。但最好别这么做。你若真想搞点自己的东西,可以看看importlib.import_module()。

from spam.ham import eggs, sausage as saus 实际上执行了

_temp = __import__(\'spam.ham\', globals(), locals(), [\'eggs\', \'sausage\'], 0)eggs = _temp.eggssaus = _temp.sausage
(本文完)请选中你要保存的内容,粘贴到此文本框

本文链接: http://maxsource16.immuno-online.com/view-770151.html

发布于 : 2021-03-25 阅读(0)
公司介绍
联络我们
服务热线:4000-520-616
(限工作日9:00-18:00)
QQ :1570468124
手机:18915418616
官网:http://