[Python3.6] print vs sys.stdout.write

Print 输出方法

使用dir()

 如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:

>>> dir('123456')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>

类似__xxx__的属性和方法在Python中都是有特殊用途的,比如__len__方法返回长度。在Python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法,所以,下面的代码是等价的:

>>> len('123456')
6
>>> '123456'.__len__()
6
>>> 

每个函数对象都是有一个__doc__的属性。通过显示__doc__,我们可以查看一些内部函数的帮助信息

>>> dir(print)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
>>> print.__doc__
"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."
>>>

我们把print的帮助信息整理一下:

1 def print(stream):  
2   """ print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)
3    
4   Prints the values to a stream, or to sys.stdout by default. 
5   Optional keyword arguments:                                            #可选参数
6   file: a file-like object (stream); defaults to the current sys.stdout. #一个类似文件的对象(流); 默认为当前的sys.stdout。
7   sep:  string inserted between values, default a space.                 #把字符串插入值(value1,value2,value3,…)之间,默认一个空格
8   end:  string appended after the last value, default a newline.         #字符串追加在最后一个值后面,默认是一个换行符。
9
flush: whether to forcibly flush the stream. #是否强行冲流。
10  """  

11 pass

猜你喜欢

转载自www.cnblogs.com/Mengchangxin/p/9115731.html