1. 苏葳的备忘录首页
  2. 编程

Python的一条简明规则和一些技巧

python dir在Python中有丰富的函数和对象方法,似乎很容易混乱。其实有一条简明的规则来分类这些功能实现的划分:可作用于多种类型的通用操作都是以内置函数或表达式形式提供的,而类型相关的操作通常会以对象方法的形式出现,如len(aa),就是通用操作,而aa.split则是针对字符串的特有操作等等。 若你定义了一个字符串a=’fff’,而你又想查看这个串支持多少属性和方法,则dir(a),会显示:

['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

一大串,很方便是不是。然后你就可以将方法传递给help函数: help(a.strip),注意必须加上前面的变量名,也许Python需要根据对象类型也确定这个方法的具体含义,才能给出帮助。

原创文章,作者:苏葳,如需转载,请注明出处:https://www.swmemo.com/425.html

发表评论

邮箱地址不会被公开。 必填项已用*标注